Overtime
Overtime

Reputation: 47

Python pop dictionary list values

I have a dictionary:

{'dict': [['IE', '5', '-5'], ['UK', '3', '-9']]}

I wish to pop the list values that are outside of the UK, therefore taking the first value within the lists and comparing to see if it is equal to 'UK'.

I currently have:

for k,v in insideUK.items():
    for i in v:
            if i[0] == "UK":
                print(x) 
            else:
                k.pop(v)

I know after the else is wrong but need help!

I wish for the dict to look like this once finished popping values that aren't equal to "UK".

{'dict': [['UK', '3', '-9']]}

Upvotes: 0

Views: 2272

Answers (3)

Maarten Fabré
Maarten Fabré

Reputation: 7058

A nested dict and list expression can do this:

{k: [i for i in v if i[0] == 'UK'] for k,v in insideUK.items()}

If you really want to do it with a for-loop and change the list in-place, you could do something like this:

for k,v in insideUK.items():
    for i in v:
            if i[0] == "UK":
                print(x) 
            else:
                v.remove(i)

But it is discouraged strongly to change the list you are iterating over during the iteration

Upvotes: 0

Vasilis G.
Vasilis G.

Reputation: 7844

You can also do it using the filter function:

d = {'dict': list(filter(lambda i: 'UK' in i, d['dict']))}
print(d)

Output:

{'dict': [['UK', '3', '-9']]}

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117981

You can use a list comprehension to filter out based on the first element

>>> data = {'dict': [['IE', '5', '-5'], ['UK', '3', '-9']]}
>>> {'dict': [i for i in data['dict'] if i[0] == 'UK']}
{'dict': [['UK', '3', '-9']]}

Upvotes: 1

Related Questions