user6882757
user6882757

Reputation:

Why is not my code working while extracting values from dict

I went through the link Accessing Python dict values with the key start characters

my = [{'k1': 'a','k2': '1234','k3':'12'},
    {'k1': 'a','k2': '1295','k3':'12'}]

for i in my:
    #print ([ v for k,v in i.items() if str(v).startswith('12')])
    print ([ v for k,v in i.items() if i['k2'].startswith('12')])

My out

['a', '1234', '12']
['a', '1295', '12874']

Expected

['1234']
['1295']

Upvotes: 1

Views: 70

Answers (2)

ggorlen
ggorlen

Reputation: 56895

You can skip the outer list and use a list comprehension:

my = [{'k1': 'a','k2': '1234','k3':'12'},
    {'k1': 'a','k2': '1295','k3':'12'}]

print([x['k2'] for x in my if x['k2'].startswith('12')])

The problem with the original code is an extra traversal over all of the entries in i if it has a key 'k2' with a value starting with '12'. It could be written as:

for i in my:
    if i['k2'].startswith('12'):
        print(i['k2'])

Note that the code raises a KeyError if 'k2' doesn't exist on one of the dicts, so you can use

[x['k2'] for x in my if 'k2' in x and x['k2'].startswith('12')]

if you anticipate this scenario.

Upvotes: 3

ExplodingGayFish
ExplodingGayFish

Reputation: 2897

You get that result because the condition i['k2'].startswith('12') always returns True. (either i['k2']='1234' or i['k2']='1295') so all the values are taken.

Upvotes: 0

Related Questions