繁体   English   中英

遍历在列表中具有列表的字典

[英]iterate through a dictionary that has a list within lists

我试图找出一种方法来匹配字典中嵌套列表中的值。 假设我有这种结构;

dict2 = {'key1': [ 2, ['value1', 3], ['value2', 4] ], 'key2' : [1, ['value1', 2], ['value2', 5] ], 'key3' : [7, ['value1', 6], ['value2', 2], ['value3', 3] ] }

现在让我们说说key1,我只想遍历列表的第一个值只是为了查找数据匹配项。 因此,如果我的数据是“ value2”,并且我想在key1中查找它,那么我希望它跳过“ 2”并检查两个列表中的第一个对象; value1,value2进行匹配,仅此而已。

尝试执行此操作,但产生了一个关键错误:1;

if 'value1' in dict2[1][1:]:
    print 'true'
else:
    print 'false'

这可能吗? 还有另一种进行匹配搜索的方法吗? 谢谢。

您问题中的代码使用数字索引而不是字符串'key1'。 这是应该起作用的修改后的版本:

if 'value1' in {array[0] for array in dict2.get('key1', [])[1:]}:
    print 'true'
else:
    print 'false'

如果字典中存在与“ key1”关联的数组中的第一个元素,则该元素将查找所有元素。

如果您确信给定的嵌套字典始终具有这种格式,那么我们可以执行以下操作:

def find_value(nested_dict, value):
    for key, nested_list in nested_dict.items():  # If Python 2, use .iteritems() instead.
        for inner_list in nested_list[1:]:
            if value == inner_list[0]:
                return True
    return False

dict2 = {'key1': [ 2, ['value1', 3], ['value2', 4] ], 'key2' : [1, ['value1', 2], ['value2', 5] ], 'key3' : [7, ['value1', 6], ['value2', 2], ['value3', 3] ] }

print(find_value(dict2, 'value2'))  # True
print(find_value(dict2, 'value5'))  # False

尝试以下方法:

if 'value1' in d['key1'][1]:
     print('Value 1 found')

if 'value2' in d['key1'][2]:
     print('Value 1 found')

如果仅在列表中查找,则可以执行以下操作:

for key, value in my_dict.items():
    for item in value:
        if isintance(item, list):
            if desired_value in item:
                return item # Here it is!

尝试这个:

for x,v in dict2.items():
   if x == "key1":
     for i, e in enumerate(v):
        try:
            if e[0] == 'value2':
               print "True"
            else: print "False"
        except:pass

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM