重复键和值的python字典

重复键和值的python字典,python,Python,我有两个数组,如下所示: a=['history','math','history','sport','math'] b=['literature','math','history','history','math'] 我压缩了两个数组,并使用dictionary查看键和值是否相等打印它们,但dictionary没有打印重复的案例,它只打印一个案例,我需要所有案例,因为我需要重复的次数 我的代码: combined_dict={} for k , v in zip(a,b): comb

我有两个数组,如下所示:

a=['history','math','history','sport','math']
b=['literature','math','history','history','math']
我压缩了两个数组,并使用dictionary查看键和值是否相等打印它们,但dictionary没有打印重复的案例,它只打印一个案例,我需要所有案例,因为我需要重复的次数

我的代码:

combined_dict={}
for k , v in zip(a,b):
    combined_dict[k]=v
    print(combined_dict)

在字典中,没有重复的键。因此,当您在第一个循环之后有
{'history':'literature'}
时,它将被
{'history':'history'}
覆盖

与其创建字典,为什么不直接循环使用
zip(a,b)


如果希望一个键具有多个值,则可以使用
集合
模块中的:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for k, v in zip(a, b):
...     d[k].append(v)
... 
>>> print(d)
defaultdict(<type 'list'>, {'sport': ['history'], 'math': ['math', 'math'], 'history': ['literature', 'history']})
>>> print(list(d.items()))
[('sport', ['history']), ('math', ['math', 'math']), ('history', ['literature', 'history'])]
>>> for k, v in d.items():
...     if k in v:
...         print k, v
... 
math ['math', 'math']
history ['literature', 'history']
>>从集合导入defaultdict
>>>d=默认DICT(列表)
>>>对于拉链中的k,v(a,b):
...     d[k]。追加(v)
... 
>>>印刷品(d)
defaultdict(,{'sport':['history'],'math':['math','math'],'history':['literature','history']})
>>>打印(列表(d.项())
[(“体育”,“历史]),(“数学”,“数学”,“数学]),(“历史”,“文学”,“历史])]
>>>对于d.项()中的k,v:
...     如果k在v中:
...         打印k,v
... 
数学['math','math']
历史[‘文学’、‘历史’]

A
dict
不能对两个条目使用相同的键。对于具有相同键的多个值,需要使用列表作为值的dict

试试这个:

from collections import defaultdict
a=['history','math','history','sport','math']
b=['literature','math','history','history','math']
combined_dict = defaultdict(list)
for k, v in zip(a,b):
    combined_dict[k].append(v)

print combined_dict

如果要获取所有项目的列表,如果两个列表之间存在匹配项,请尝试

>>> print [k for k, v in zip(a, b) if k == v]
    ['math', 'history', 'math']

这将为您提供一个匹配项目的列表,您可以进一步处理这些项目。

谢谢。您的第一个建议工作正常,这就是我的意思。那么,您能告诉我如何将所有结果项保存在一个列表中,以便计算该列表中项目的最终数量吗?@Basira将一个列表放在另一个列表中?您可以执行
a.extend(b)
>>> print [k for k, v in zip(a, b) if k == v]
    ['math', 'history', 'math']