Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

python - List of tuples to nested dictionary without overriding

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's one way to do it with collections.defaultdict:

from collections import defaultdict
import pprint

data = [('a', '1'), ('b', 'true'), ('b', 'none'), ('a', '2'), ('b', 'true'), ('a', '3'), ('b', 'false')]

d = defaultdict(lambda: defaultdict(lambda: defaultdict(tuple)))    
for i, j in data:
    if i == 'a':
        p = d[i][j]
    else:
        p[i] += j,

pprint.pprint(d)
# {'a': {'1': defaultdict(<class 'tuple'>, {'b': ('true', 'none')}),
#        '2': defaultdict(<class 'tuple'>, {'b': ('true',)}),
#        '3': defaultdict(<class 'tuple'>, {'b': ('false',)})}}

You could also use the dictionary's setdefault method to return default values for new keys, although the defaultdict approach is much cleaner and faster:

c = {}
for i, j in data:
    if i == 'a':
        q = c.setdefault(i, {}).setdefault(j, {})
    else:
        q[i] = q.setdefault(i, ()) + (j,)

pprint.pprint(c)
# {'a': {'1': {'b': ('true', 'none')},
#        '2': {'b': ('true',)},
#        '3': {'b': ('false',)}}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...