A
A
Andrei Sayevich2020-07-03 00:07:18
Python
Andrei Sayevich, 2020-07-03 00:07:18

Dictionary lists Oddity or bug?

The task was like this ...
you need to sort the list of dictionaries and
leave only dictionaries with the country Russia there

x = "Россия"
geo_logs = [
    {'visit1': ['Москва', 'Россия']},
    {'visit2': ['Дели', 'Индия']},
    {'visit3': ['Владимир', 'Россия']},
    {'visit4': ['Лиссабон', 'Португалия']},
    {'visit5': ['Париж', 'Франция']},
    {'visit6': ['Лиссабон', 'Португалия']},
    {'visit7': ['Тула', 'Россия']},
    {'visit8': ['Тула', 'Россия']},
    {'visit9': ['Курск', 'Россия']},
    {'visit10': ['Архангельск', 'Россия']},
    {'visit11': ['Минск', 'Беларусь']},
    {'visit12': ['Париж', 'Франция']}
]

for element in geo_logs:
    for visit, country in element.items():
        if country[1] != x:
            geo_logs.remove(element)
print(geo_logs)


I wrote a code which in my view should simply remove elements that do not contain "Russia", but it does not remove for me, not only that, but also that which contains "France"

Can someone explain what's wrong and why it happens?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
ScriptKiddo, 2020-07-03
@Soerrrrrrr

You can't iterate over a list and remove elements at the same time. Iterate over the copy and remove from the original array.
for element in geo_logs[:]:

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question