I need to convert the above list of tuples to nested dictionary without overwriting the value as below in python
[('a', '1'),
('b', 'true'),
('b', 'none'),
('a', '2'),
('b', 'true'),
('a', '3'),
('b', 'false')]
{'a': {'1' : { 'b' : ('true','none')},
'2' : { 'b' : ('true')},
'3' : { 'b' : ('false')}}}
Converting each tuple into dictionary using
dict()
and merging the dictionary doesn't work. Is there any pythonic way to do this?
Here's one way to do it with
collections.defaultdict
:You could also use the dictionary's
setdefault
method to return default values for new keys, although thedefaultdict
approach is much cleaner and faster:Expanding @MosesKoledoye answer, if the first value in the dictionary is only
'a'
and'b'
, you know that the outer dictionary will always contain at most one element using'a'
as the key and the inner dictionary will always contain at most one element using'b'
as the key. So in the end you get the same information if it is{'1': ('true', 'none')…
. You can convert that to your format simply by wrapping the data in some dictionaries. This means you can do the followingThis will result in the following:
Now to get it into a dictionary like yours you can do the following:
Resulting in the following: