-1

UPD: inserting from collections import OrderedDict into one of my code cells helped

I want to make a program which accepts a string and then outputs dictionary where each element is this string's character with an index.

Input: hello

Output {'h': 1, 'e': 2, 'l': 3, 'l': 4, 'o': 5}

I've come up with several ways to create this kind of dictionary. However, in every case I have the following output with above-mentioned input: {'e': 2, 'h': 1, 'l': 4, 'o': 5}

#solution 1
s = str(input())
dic = {}
for index, symb in enumerate(s, 1):
  dic[symb]=index
dic

#soultion 2
s = input()
d4 = {}
d4 = dict(zip(s,range(1,len(s)+1)))
d4

What can be an issue here? I will appreciate any help. THanks in advance.

P.S. for coding I use Google Collab

JoshJohnson
  • 181
  • 3
  • 18

3 Answers3

1

Dictionaries only allow for one value per key, therefore there won't be two values for the key l, no matter how hard you try. Also, dictionaries are unordered, so the items won't appear in the order they were inserted.

Seth
  • 2,214
  • 1
  • 7
  • 21
1
    Simple and Easy:-
    v_str='hello'
    class Dictlist(dict):
    def __setitem__(self, key, value):
        try:
            self[key]
        except KeyError:
            super(Dictlist, self).__setitem__(key, [])
        self[key].append(value)

p_dict=Dictlist()
for i, j in enumerate(v_str):
    p_dict[j]=i
print(p_dict)

# output:-{'h': [0], 'e': [1], 'l': [2, 3], 'o': [4]}
0

As @IoaTzimas points out correctly in the comments is that you have fundamental misunderstanding of how dict keys work. dict keys must be unique (think like a house key) because the key maps to the value.

griffin_cosgrove
  • 419
  • 8
  • 16