3级嵌套字典中的存在性测试

时间:2014-03-27 02:59:30

标签: python dictionary

我有以下字典:

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"

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

考虑使用dict.get

您可能想要执行mydict.get("Foo", {}).get(ct, {}).get(ch):之类的操作。基本上会得到一个默认的空dict,默认情况下会在结尾处默认为空。

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

这样的东西
if ct in mydict['foo'] and ch in mydict['foo'][ct]:

由于Python中的延迟评估,这不会失败。

答案 2 :(得分:1)

您可以使用any函数和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

答案 3 :(得分:1)

您使用的是错误的变量名称

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][ch]: // change choices to ch
            print "THERE\n"
        else:
            print "Not there\n"
相关问题