'How can I print duplicate items from an OrderedDict?

My OrderedDict contains 5 key value pairs which result in the word, Belle. Every letter it's own key with values starting from 1 through 5, from left to right, B = 1, e = 2, etc. Printing this OrderedDict returns only 3 letters, B, l and e. Notice, it doesn't print the repeated e's and l's. In the code below, I use a for statement to print "Belle" so it can print vertically. My goal is to print the complete word "Belle" vertically, with each letter as a key with it's value pair.

text6 = OrderedDict({'B':1, 'e':2, 'l':3, 'l':4, 'e':5}) for key, value in text6.items(): print(key, value)

#Code above returns: B 1 e 5 l 4

#Desried output: B 1 e 2 l 3 l 4 e 5



Solution 1:[1]

Asking a dict (including OrderedDict) to do what you are asking it to do is impossible. A dict of any type can only contain unique keys. All subsequently added pre-existing keys will overwrite the key and reset it's value.

Another reason a dict will not work for your desired ordered output is that dict keys are unordered. I suspect this is why you tried to overcome this with the OrderedDict approach, but remember we still cannot overcome the fact that only unique keys can be contained in a dictionary. So 'l' in 'Belle' will end up holding the value 3 when it overwrites it's previous value which was 2 previously. In the end you are seeing the final result of this mutated dictionary.

In order to get the output you want to see, we can use a different data structure. In this implementation, we utilize a list which will contain a tuple for each (value, index) pair we will get by iterating through "Belle" using enumerate

list((v, i) for i, v in enumerate("Belle", 1))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1