Assigning Keys To A Dictionary From A String
Solution 1:
You could do something like this:
result = {}
s = 'the sly fox jumped over the brown dog'for i, c in  enumerate(s):
    result.setdefault(c, []).append(i)
print(result)
Output
{'m': [14], 'e': [2, 16, 21, 26], 'v': [20], 's': [4], 'n': [32], 'h': [1, 25], 'w': [31], 'l': [5], 'o': [9, 19, 30, 35], 'x': [10], 'p': [15], 'd': [17, 34], 'g': [36], 't': [0, 24], 'u': [13], 'f': [8], 'y': [6], 'b': [28], 'j': [12], ' ': [3, 7, 11, 18, 23, 27, 33], 'r': [22, 29]}
Note that the above solution contemplates the case for repeated characters and it creates a list of the indices.
Solution 2:
since the character might be repeated in string, i am storing them as a list
str = "the sly fox jumped over the brown dog"
char_items = list(str) 
dictionary = {}
for index,character inenumerate(char_items): 
    if character notin dictionary.keys():
        dictionary[character] = [] # because same character might be repeated in different positions
    dictionary[character].append(index)
for character,positions in dictionary.items():
    print(character, positions)
Solution 3:
Thanks, all, for suggestions! As Asif suggested above, the way forward for me was to convert the string into a list. 👍🏼
I also found 'three ways of creating dictionaries in Python', by Nick Dunn really useful: https://developmentality.wordpress.com/2012/03/30/three-ways-of-creating-dictionaries-in-python/
The three steps I used:
EXAMPLE PROBLEM: "Create a dictionary with keys consisting of the characters in alphabet(' abcdefghijklmnopqrstuvwxyz'), and values consisting of the numbers from 0 to 26. Store this as positions."
1) Turn alphabet from a string into a list, chars
chars = []
for AtoZ in alphabet:
chars += AtoZ
print(chars)
[' ',
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z']
2) create a second list called numbers
numbers = list(range(0,27))
numbers
Out[16]: 
[0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26]
3) Create the dictionary called positions{} from the two lists:
positions = {}
positions = dict(zip(chars,numbers))
print(positions)
{'v': 22, 'g': 7, 'w': 23, 'h': 8, 'a': 1, 'm': 13, 'c': 3, 'o': 15, 'd': 4,  's': 19, 'r': 18, 'u': 21, 'j': 10, 't': 20, 'f': 6, 'k': 11, 'y': 25, 'z': 26, 'l': 12, ' ': 0, 'b': 2, 'e': 5, 'q': 17, 'n': 14, 'i': 9, 'p': 16, 'x': 24}
😊 I hope this post helps others converting strings and/or lists into dictionaries using Python.
Post a Comment for "Assigning Keys To A Dictionary From A String"