python - 如何将一个列表中的值与Python列表字典中的唯一值相匹配

标签 python list dictionary

所以我的输入值如下:

temp_dict1 = {'A': [1,2,3,4], 'B':[5,5,5], 'C':[6,6,7,8]}
temp_dict2 = {}
val = [5]

列表 val 可能包含更多值,但目前它只包含一个。我想要的结果是:

>>>temp_dict2
{'B':[5]}

最终的字典只需要包含列表 val 中包含该项目的列表的键,以及列表中该值的唯一实例。我尝试按如下方式迭代这两个对象:

for i in temp_dict1:
    for j in temp_dict1[i]:
        for k in val:
            if k in j:
                temp_dict2.setdefault(i, []).append(k)

但这只是返回一个argument of type 'int' is not iterable错误消息。有什么想法吗?

最佳答案

更改了您的词典以涵盖更多情况:

temp_dict1 = {'A': [1,2,3,4], 'B':[5,5,6], 'C':[6,6,7,8]}
temp_dict2 = {}
val = [5, 6]

for item in val:
    for key, val in temp_dict1.items():
        if item in val:
            temp_dict2.setdefault(key, []).append(item)

print(temp_dict2)
# {'B': [5, 6], 'C': [6]}

或者,使用列表理解相同(看起来有点难以理解,不推荐)。

temp_dict2 = {}
[temp_dict2.setdefault(key, []).append(item) for item in val for key, val in temp_dict1.items() if item in val]

关于python - 如何将一个列表中的值与Python列表字典中的唯一值相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49348944/

相关文章:

python - 在函数中引用 DataFrame 名称(pandas、python3)

Python - 如何将嵌套列表拆分为更多列表?

python - 在 python 字典中编辑值

python - 对字典列表应用集合操作

c# - 如何根据类中属性的类型动态创建 C# 泛型字典?

python - PySpark作业抛出IOError

python - 将 CudaNdarraySharedVariable 转换为 TensorVariable

python - 在python中使用递归查找树中的节点

python - !从无序列表中绘制一个形状 Python

python - 如何在 Python 中将列表初始化为某个值