检查2个不同词典中的相同键,打印键和两个值

时间:2017-04-20 16:58:53

标签: python dictionary counter

我不知道为什么我无法解决这个问题,但我希望程序能够查看2个字典,如果密钥匹配,我希望它能够打印密钥以及两个字典中的值,如此...

[结果]

a 1 2
b 2 4
c 3 6
d 4 8

[CODE]

from collections import Counter

a = Counter({'a':1,'b':2,'c':3,'d':4})
b = Counter({'a':2,'b':4,'c':6,'d':8})

for key in b.most_common():
    if set(a.keys()) == set(b.keys()):
        print(key)

3 个答案:

答案 0 :(得分:4)

您可以迭代这两个键的set intersection

>>> set(a.keys()) & set(b.keys())
set(['a', 'c', 'b', 'd'])

这里有一个不完全相似的词组的例子:

from collections import Counter

a = Counter({'a':1,'b':2,'c':3,'d':4,'e':5})
b = Counter({'a':2,'b':4,'c':6,'d':8,'f':7})

common_keys = set(a.keys()) & set(b.keys())

for key in common_keys:
    print("%s %d %d" % (key, a[key], b[key]))
# a 1 2
# c 3 6
# b 2 4
# d 4 8

请注意,转换为set并不会预先Counter订单。

您可以将set转换为list并根据两个值的总和对其进行排序:

a = {'a':1,'b':2,'c':3,'d':4,'e':5}
b = {'a':2,'b':4,'c':6,'d':8,'f':7}

common_keys = list(set(a.keys()) & set(b.keys()))

common_keys.sort(key=lambda k: a[k] + b[k], reverse=True)

for key in common_keys:
    print("%s %d %d" % (key, a[key], b[key]))
# d 4 8
# c 3 6
# b 2 4
# a 1 2

最后,如果您不在乎根据其值的总和对键进行排序,请参阅稍微修改过的代码版本:

from collections import Counter

a = Counter({'a':1,'b':2,'c':3,'d':4})
b = Counter({'a':2,'b':4,'c':6,'d':8})

for key, a_value in a.most_common():
    if key in b:
        print("%s %d %d" % (key, a_value, b[key]))

答案 1 :(得分:0)

common_keys = sorted(set(a.keys()).intersection(b.keys()))

for key in common_keys:
    print(key, a[key], b[key])

答案 2 :(得分:0)

您几乎就在那里,public class PriceLookupGrid { public int VendorID { get; set; } public string VendorName { get; set; } public string Description { get; set; } public int MaterialTypeID { get; set; } public string MaterialType { get; set; } public string NewPrice { get; set; } public string RemodelPrice { get; set; } public string ServicePrice { get; set; } public string SellUOM { get; set; } public string Cost { get; set; } public string PurchaseUOM { get; set; } } 条件已关闭,if会返回元组列表,因此您需要解压缩键值对

most_common

如果您不关心订单,(即您不需要致电>>> a = Counter({'a':1,'b':2,'c':3,'d':4}) >>> b = Counter({'a':2,'b':4,'c':6,'d':8}) >>> for key, bval in b.most_common(): ... if key in a: ... print(key, a[key], bval) ... d 4 8 c 3 6 b 2 4 a 1 2 >>> ),您可以迭代交叉路口。在python 3中,这很容易:

most_common

因为>>> a.keys() & b.keys() {'d', 'a', 'c', 'b'} >>> 实际上返回的视图更像是集合而不是列表。

.keys