我想比较两个词典键,如果有匹配,我想用键和两个词典中的值创建一个新词典,如果没有匹配,我想把值设为0。
我尝试了以下代码,但是当我尝试打印不在第一个词典KeyError: 't2.large'
中的此键时,我得到了a
。
c = dict()
a = {'m3.xlarge': 4, 't2.medium': 1, 't2.large': 1, 'm3.large': 1}
b = {'m3.xlarge': 5, 't2.medium': 1, 'm3.large': 2, 'm4.large': 1}
c = dict()
for key, value in a.items():
if key in b.keys():
a_key = key
a_value = value
b_value = b[key]
c.setdefault(a_key,[]).append(a_value)
c.setdefault(a_key,[]).append(b_value)
elif key not in b.keys():
value = b.get(key)
print("key not in b.keys() => ", value) # key not in b.keys() => None
b_value = b[key]
print("key a not in b.keys => ", b_value) # KeyError: 't2.large'
print(c)
结果应该是这样的:
# c = {'m3.xlarge': [4, 5], 't2.medium': [1, 1], 't2.large': [1, 0], 'm3.large': [1, 2], 'm4.large': [0, 1]}
我的第二个问题,我如何做同样的事情,但没有附加密钥:如果两个字的密钥:值之间存在匹配,则为新字典添加值。
't2.medium': [1, 1] will be removed because the keys:values are the same 1-1
c = {'m3.xlarge': [4, 5], 't2.large': [1, 0], 'm3.large': [1, 2], 'm4.large': [0, 1]}
谢谢!
答案 0 :(得分:3)
您的代码效率很低。错误发生在这里:
rspec spec --deprecation-out /dev/null
在此,您知道elif key not in b.keys():
#...
b_value = b[key]
不是key
的元素,但您可以查询它。
然而,优雅的单行将是:
b
这将替换您编写的所有代码。但是,根据您的示例输出,您可能需要将其替换为:
c = {key:[val,b.get(key,0)] for key,val in a.items()}
甚至更优雅:
c = {key:[val,b.get(key,0)] for key,val in a.items()}
c.update({key:[a.get(key,0),val] for key,val in b.items()})
在终端中运行时,我得到:
c = {key:[a.get(key,0),b.get(key,0)] for key in set(a)|set(b)}
(2):要回答第二个问题,您可以添加过滤器:
$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = {'m3.xlarge': 4, 't2.medium': 1, 't2.large': 1, 'm3.large': 1}
>>> b = {'m3.xlarge': 5, 't2.medium': 1, 'm3.large': 2, 'm4.large': 1}
>>> c = {key:[val,b.get(key,0)] for key,val in a.items()}
>>> c.update({key:[a.get(key,0),val] for key,val in b.items()})
>>> c
{'t2.medium': [1, 1], 'm3.xlarge': [4, 5], 'm3.large': [1, 2], 'm4.large': [0, 1], 't2.large': [1, 0]}
>>> c = {key:[a.get(key,0),b.get(key,0)] for key in set(a)|set(b)}
>>> c
{'t2.medium': [1, 1], 'm3.xlarge': [4, 5], 't2.large': [1, 0], 'm3.large': [1, 2], 'm4.large': [0, 1]}
答案 1 :(得分:3)
如果您正在使用两个词典中的键查找列表,则可以使用:
a = {'m3.xlarge': 4, 't2.medium': 1, 't2.large': 1, 'm3.large': 1}
b = {'m3.xlarge': 5, 't2.medium': 1, 'm3.large': 2, 'm4.large': 1}
c = dict()
for key in set(a.keys() | b.keys()):
c[key] = [a.get(key, 0), b.get(key, 0)]
导致
{'t2.medium': [1, 1], 't2.large': [1, 0], 'm3.large': [1, 2], 'm4.large': [0, 1], 'm3.xlarge': [4, 5]}
我们可以合并第二个标准(虽然不是特别优雅),并按如下方式减少到一行:
c = {key: [a.get(key, 0), b.get(key, 0)] for key in set(a.keys() | b.keys()) if a.get(key, 0) != b.get(key, 0)}
注意:在Python 2.7中,您需要使用a.keys() + b.keys()
而不是a.keys() | b.keys()