三级嵌套字典的存在性测试

2024-06-22 10:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下词典:

In [32]: mydict
Out[32]: 
{'Foo': {'DendriticCells': {'LV.ip': [15.14,1.003],
   'SP.ip': [16.0282,3.001]},
  'Macrophages': {'LV.ip': [32.137260000000005],
   'SP.ip': [34.020810000000004]},
  'NKCells': {'LV.ip': [4.89852], 'SP.ip': [5.18562]}}}

给定一个对应于键级别3的字符串,我要做的是构造一个 根据下面的choices检查字典中是否存在。 怎么做呢。我试过但失败了。你知道吗

choice1 = "LV.ip"
choice2 = "KK.ip"
choices = [choice1,choice2]
celltypes = ["DendriticCells",  "Macrophages", "NKCells"]
for ch in choices:
    for ct in celltypes:
        if mydict["Foo"][ct][choices]:
            print "THERE\n"
        else:
            print "Not there\n"

Tags: inipforfoospmydictchoicesct
3条回答

您可以使用^{}函数和in运算符来检查字典中是否存在键。你知道吗

for choice in choices:
    for key in my_dict:
        if any(choice in my_dict[key][key1] for key1 in my_dict[key]):
            print "{} is there".format(choice)

输出

LV.ip is there
  1. 你的if语句应该使用ch,而不是choices
  2. 您应该在if中分解测试;例如,在尝试查看它是否包含任何内容之前,请确保mydict["Foo"][ct]存在。你知道吗

考虑使用^{}。你知道吗

您可能需要执行类似mydict.get("Foo", {}).get(ct, {}).get(ch):的操作。基本上得到一个默认的空dict,它将在最后默认为nothing。你知道吗

或者,使用in验证密钥。你可能有

if ct in mydict['foo'] and ch in mydict['foo'][ct]:

它不应该因为Python中的延迟计算而失败。你知道吗

相关问题 更多 >