0

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']]}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Overtime
  • 47
  • 10

3 Answers3

1

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']]}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

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']]}
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
0

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

Maarten Fabré
  • 6,938
  • 1
  • 17
  • 36