user1165419
user1165419

Reputation: 663

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. 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; value1, value2 for a match and that's it.

Tried doing this but it gave a keyerror: 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.

Upvotes: 0

Views: 92

Answers (5)

Merlin
Merlin

Reputation: 25629

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

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78546

Try this instead:

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

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

Upvotes: 0

Bo Borgerson
Bo Borgerson

Reputation: 1406

The code in your question is using a numeric index instead of the string '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.

Upvotes: 2

Aquiles
Aquiles

Reputation: 881

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!

Upvotes: 0

Adriano
Adriano

Reputation: 1723

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

Upvotes: 1

Related Questions