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
745 views
in Technique[技术] by (71.8m points)

dictionary - To merge two dictionaries of list in Python

There are two dictionaries

x={1:['a','b','c']}
y={1:['d','e','f'],2:['g']}

I want another dictionary z which is a merged one of x and y such that

z = {1:['a','b','c','d','e','f'],2:['g']}

Is it possible to do this operation? I tried update operation

x.update(y)

But it gives me the following result

z= {1:['d','e','f'],2:['g']}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
for k, v in x.items():
if k in y.keys():
    y[k] += v
else:
    y[k] = v

Loop through dictionary getting keys and values, check if the key already exists, in which case append, else add new key with values. It won't work if your values are mixed data types that aren't lists, like you have.

   x={1:['a','b','c'], 3:['y']} 
.. y={1:['d','e','f'],2:['g']} 
..  
..  
.. for k, v in x.items(): 
..     if k in y.keys(): 
..         y[k] += v 
..     else: 
..         y[k] = v 
..      
.. print y
{1: ['d', 'e', 'f', 'a', 'b', 'c'], 2: ['g'], 3: ['y']}

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

...