[英]How to compare the values in two dictionaries (as a list with multiple list entries) in python
我正在尝试比较两个字典一个键:每个值对。 两个字典中的键不同。 这些值由多个数字组成。 我想查找两个字典中都出现的所有值数字,但是我的代码返回以下错误:不可哈希类型:“列表”。 有什么想法可以解决这个错误吗? 预先感谢您的支持!
d_MS = {"74286565":[1672118498, 72935438163394562, 3597763396, 1099812539549011970]}
d_eco = {"36146779": [170742628, 3597763396, 247113642, 1130696607027138560, 162853322]}
d1_values = set(d_MS.values())
d2_values = set(d_eco.values())
in_both = d1_values & d2_values
not_in_both = d1_values ^ d2_values
我想得到的是两个字典中都出现的所有数字的列表,在本示例中,这将是
[3597763396]
两个给定集合A和B的交集是一个集合,它由A和B共同的所有元素组成。
例如
d_MS = {"74286565":[1672118498, 72935438163394562, 3597763396, 1099812539549011970]}
d_eco = {"36146779": [170742628, 3597763396, 247113642, 1130696607027138560, 162853322]}
x = list(set(d_MS['74286565']).intersection(d_eco['36146779']))
#or
#x = list(set(*d_MS.values()).intersection(*d_eco.values()))
print(x)
O / P:
[3597763396]
与*一起使用,它将把值解压缩到列表中,因为.values()
返回dict_values
对象。
d_MS = {"74286565":[1672118498, 72935438163394562, 3597763396, 1099812539549011970]}
d_eco = {"36146779": [170742628, 3597763396, 247113642, 1130696607027138560, 162853322]}
d1_values = set(*d_MS.values())
d2_values = set(*d_eco.values())
in_both = d1_values & d2_values
not_in_both = d1_values ^ d2_values
print(in_both)
print(not_in_both)
输出:
{3597763396}
{1130696607027138560, 247113642, 1099812539549011970, 1672118498, 170742628, 72935438163394562, 162853322}
如果您的用例需要列表,则可以执行以下操作:
list(in_both)
输出量
[3597763396]
注意 :仅当您在用例中指定了一个key:value对时,该方法才有效。
.values()
方法返回一个dict_values
对象,将其转换为列表,该列表将返回带有值的的列表。 在这种情况下,只有一个值本身就是一个列表。
d_MS = {"74286565":[1672118498, 72935438163394562, 3597763396, 1099812539549011970]}
d_eco = {"36146779": [170742628, 3597763396, 247113642, 1130696607027138560, 162853322]}
# here the `dict_value` object is converted into a list, and the list of values
# has the one item, which was a list in the first place hence the indexing
d1_values = set(list(d_MS.values())[0])
d2_values = set(list(d_eco.values())[0])
in_both = d1_values & d2_values
not_in_both = d1_values ^ d2_values
print(in_both, not_in_both)
这将打印
{3597763396} {1130696607027138560, 247113642, 1099812539549011970, 1672118498, 170742628, 72935438163394562, 162853322}
另一种方法是从dict_values
对象解压缩值,然后set(*d_MS.values())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.