复杂字典的迭代



我有如下字典,如您所见,我正在尝试打印字典中没有的key_p。我想检查我的key_p是否存在于字典中,打印值以及当key_p不在字典中时打印0

当我输入条件elif时,它将0打印两次(=字典中的元素数量(,但我只想检查key_p,这意味着如果key_p在字典打印中,1如果只有key_p不在字典打印0中。

sc_dict = [('fl', {'ab': 1}), ('fl', {'abel': 1})]
key_p = "tep"
for row in sc_dict:
 sc = row[1]
for field, values in sc.items():
   if field == key_p:
      print("1")
   elif field != key_p:
      print("0")

首先sc_dict是一个列表,而不是字典。

从你的代码来看,我理解你的问题如下:在sc_dict持有的元组内的字典中,你想检查是否有任何包含特定键。

这里有一种方法,使用 any 内置函数(它返回一个布尔值,我们根据您的要求将其转换为int(和元组解包:

>>> sc_list = [('fl', {'ab': 1}), ('fl', {'abel': 1})]
>>> key = 'key_p'
>>> int(any(key in d for _, d in sc_list))
0
>>> key = 'abel'
>>> int(any(key in d for _, d in sc_list))
1

根据您的实际问题是什么,从字典中构建ChainMap可能是有益的。下面的示例介绍了该概念,并解决了原始问题。

>>> from collections import ChainMap
>>> cm = ChainMap(*(d for _, d in sc_list))
>>> cm
ChainMap({'ab': 1}, {'abel': 1})
>>> int('key_p' in cm)
0
>>> int('abel' in cm)
1

下面是如何执行此操作的示例:

sc_dict=[('fl', {'ab': 1}), ('fl', {'abel': 1})]
key_p="tep"
dict_part = [sc[1] for sc in sc_dict]
together = {}
for item in dict_part:
    together.update(item)
print(together.get(key_p, 0))

最新更新