I would like to turn a dictionary into an “ordered” dictionary - i have an example here:
Dict1 = {
‘tim’ : ‘apple’,
‘bob’ : ‘banana’,
‘kim’ : ‘banana’,
‘bo’ : ‘apple’,
‘joe’ : ‘apple’
}
should return something like:
‘apple’ : [‘tim’, ‘bo’, ‘joe’],
‘banana’ : [‘bob’, ‘kim’]
How would I get around this? is there a built-in function or should i create this myself?
thanks!
tjol
(Thomas Jollans)
October 26, 2021, 7:56am
2
Hi Sören,
Python comes with a type called OrderedDict , but it’s very different from what you’re imagining. It’s also a pretty niche type since Python 3.7 - before then the order of keys in a dict was undefined.
It’s relatively easy to sort a dict by its keys:
>>> d
{'tim': 'apple', 'bob': 'banana', 'kim': 'banana', 'bo': 'apple', 'joe': 'apple'}
>>> dict(sorted(d.items()))
{'bo': 'apple', 'bob': 'banana', 'joe': 'apple', 'kim': 'banana', 'tim': 'apple'}
>>>
While this is what the title of your post suggests you want, it’s not what you’re actually asking, so let’s get on to that
Luckily, this sort of manipulation is generally easy to do in Python. For your problem, I’d use defaultdict :
>>> from collections import defaultdict
>>> result = defaultdict(list)
>>> d
{'tim': 'apple', 'bob': 'banana', 'kim': 'banana', 'bo': 'apple', 'joe': 'apple'}
>>> for (key, value) in d.items():
... result[value].append(key)
...
>>> result
defaultdict(<class 'list'>, {'apple': ['tim', 'bo', 'joe'], 'banana': ['bob', 'kim']})
>>>
BowlOfRed
(BowlOfRed)
October 26, 2021, 8:07am
3
Dict1 = {
'tim' : 'apple',
'bob' : 'banana',
'kim' : 'banana',
'bo' : 'apple',
'joe' : 'apple'
}
transposed = {}
for k,v in Dict1.items():
transposed.setdefault(v, []).append(k)
print(transposed)
{'apple': ['tim', 'bo', 'joe'], 'banana': ['bob', 'kim']}
1 Like
Thanks a lot both! this was exactly the methods i was looking for!