我有2个字典,如下:
a = [{'泉州seo': '2,1'}, {'泉州网站建设': '1'}, {'泉州网络公司': ''}, {'泉州微信小程序': ''}]
b = [{'泉州seo': ''}, {'泉州网站建设': ''}, {'泉州网络公司': ''}, {'泉州微信小程序': '15,34'}]
2个字典分别存放的是我一些数据,我现在想要的效果是把a和b合并起来显示,比如这样:
c = [{'泉州seo': '2,1'}, {'泉州网站建设': '1'}, {'泉州网络公司': ''}, {'泉州微信小程序': '15,34'}]
就是这样一个简单的效果!
请问要如何用最简单的代码来实现!
欢迎高手挑战!
怪我咯2017-04-18 10:26:55
It seems like a dictionary shouldn’t be used like this...
The answer I want to give is
c = {k:d1[k]+d2[k] for d1,d2 in zip(a,b) for k in d1}
But according to the requirement, the answer should be
c = [{k:d1[k]+d2[k]} for d1,d2 in zip(a,b) for k in d1]
黄舟2017-04-18 10:26:55
Compare the value of each dictionary in a with the value of each dictionary in b. If the value of the dictionary in b is greater than the value of the corresponding dictionary of a, copy it and assign it to c.
>>> a = [{'s1': '2,1'}, {'s2': '1'}, {'s3': ''}, {'s4': ''}]
>>> b = [{'s1': ''}, {'s2': ''}, {'s3': ''}, {'s4': '15,34'}]
>>> for i in range(len(a)):
if cmp(a[i],b[i]) < 0:
a[i] = b[i].copy()
>>> c = a
>>> print c
[{'s1': '2,1'}, {'s2': '1'}, {'s3': ''}, {'s4': '15,34'}]