Home > OS >  How to store the positions of an element in string in a dictionary (Python)?
How to store the positions of an element in string in a dictionary (Python)?

Time:11-28

I want to get all the positions (indexes) of an element in a string and store them in a dictionary.

This is what I've tried:

string = "This is an example"       
test = {letter: pos for pos, letter in enumerate(string)}

But this only gives the last position of the letter. I'd like all positions, desired output:

test["a"]
{8, 13}

CodePudding user response:

At the moment you are overwriting the dictionary values. For example,

>>> my_dict = {}
>>> my_dict['my_val'] = 1 # creating new value
>>> my_dict
{'my_val': 1}
>>> my_dict['my_val'] = 2 # overwriting the value for `my_val`
>>> my_dict
{'my_val': 2}

If you want to keep all values for a key you can use a list along with dict.setdefault method .

>>> print(dict.setdefault.__doc__)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
>>>
>>> result = {}
>>> string = "This is an example"
>>> 
>>> for index, value in enumerate(string):
...     result.setdefault(value, []).append(index)
... 
>>> result["a"]
[8, 13]

CodePudding user response:

FOR LIST

Creating a dictionary with the keys being the characters in the input_string and the characters being the

indices of the characters in the input_string.

output = {}

Creating a input_string variable called input_string and assigning it the character "This is an example"

input_string = "This is an example"

Iterating through the input_string and assigning the index of the character to index and the character

to character.

output.setdefault(character, []) is checking if the key character exists in the dictionary output. If it does not exist, it will create the key character and assign it the character []. If it does exist, it will return the character of the key character. Then, .append(index) will append the character of index to the character of the key character.

for index, character in enumerate(input_string):
    output.setdefault(character, []).append(index) 
   

Desired Output

output["i"]
[2, 5]

In SORT CODE BE LIKE:-

output = {}

input_string = "This is an example"

for index, character in enumerate(input_string):
    output.setdefault(character, []).append(index) 
   

FOR DICT/SET


Creating a dictionary with the keys being the characters in the input string and the values being

the indices of the characters in the input string.

output = {}

input_string = "This is an example"

for index, character in enumerate(input_string):
    output.setdefault(character, set()).add(index) 
   
  • Related