简体   繁体   English

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

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

I'm trying to figure out a way to match a value in a nested list in a dictionary. 我试图找出一种方法来匹配字典中嵌套列表中的值。 Let's say I have this structure; 假设我有这种结构;

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

Now let's say for key1, I want iterate through the first value of the lists only to look for a data match. 现在让我们说说key1,我只想遍历列表的第一个值只是为了查找数据匹配项。 So if my data is "value2" and i want to look for it in key1, then I want it to skip the '2' and check the first object in the two lists which are; 因此,如果我的数据是“ value2”,并且我想在key1中查找它,那么我希望它跳过“ 2”并检查两个列表中的第一个对象; value1, value2 for a match and that's it. value1,value2进行匹配,仅此而已。

Tried doing this but it gave a keyerror: 1; 尝试执行此操作,但产生了一个关键错误:1;

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

Is this possible to do? 这可能吗? Is there another way to do match search? 还有另一种进行匹配搜索的方法吗? Thanks. 谢谢。

The code in your question is using a numeric index instead of the string 'key1'. 您问题中的代码使用数字索引而不是字符串'key1'。 Here's a modified version that should work: 这是应该起作用的修改后的版本:

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

That looks at all of the elements after the first in the array associated with 'key1' in your dictionary, if it exists. 如果字典中存在与“ key1”关联的数组中的第一个元素,则该元素将查找所有元素。

If you're confident that the given nested dictionary always has this format, then we can do something like: 如果您确信给定的嵌套字典始终具有这种格式,那么我们可以执行以下操作:

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

Try this instead: 尝试以下方法:

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

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

If you are looking only inside the lists you may do something like this: 如果仅在列表中查找,则可以执行以下操作:

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!

Try this: 尝试这个:

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