sam
sam

Reputation: 1290

String to dict with duplicates

I think I am missing something basic here. I was trying to split a string into a dict with key as the index and value as the character.

instring = 'aabc'
stringmap = {instring.index(i): i for i in instring}

When I print stringmap: {0: 'a', 2: 'b', 3: 'c'}

I was expecting

{0: 'a', 1: 'a', 2: 'b', 3: 'c'}

What am I missing? The index values are right, but the duplicates are not part of the dict.

Upvotes: 0

Views: 200

Answers (2)

Alain T.
Alain T.

Reputation: 42143

The index(i) method always returns the index of the first occurrence. That's why you get duplicate keys (i.e. zero for both instances of the letter a).

Simply feeding enumerate to the dict constructor will do the trick:

stringmap = dict(enumerate(instring))

Upvotes: 3

Sohaib Anwaar
Sohaib Anwaar

Reputation: 1547

Hey @sam You can solve your problem with this.

string = "sohaib"

{index:i for index,i in enumerate(string)}

Answer

{0: 's', 1: 'o', 2: 'h', 3: 'a', 4: 'i', 5: 'b'}

Upvotes: 2

Related Questions