I have a list of dicts like this:
zip_values = [{'Spain': '43004'}, {'Spain': '43830'}, {'Spain': '46003'}, {'Spain': '50006'}, {'Portugal': ''}, {'Portugal': '1000-155'}, {'Portugal': '1000-226'}, {'Portugal': '1050-175'}, {'Portugal': '1050-190'}, {'Portugal': '1070-041'}, {'Portugal': '1150-101'}, {'Portugal': '1150-260'}, {'Portugal': '1200-114'}, {'Portugal': '1250-192'}, {'Portugal': '1300-243'}, {'Portugal': '1300-610'}, {'Portugal': '1350-100'}, {'Portugal': '1400-140'}, {'Portugal': '1400-212'}, {'Portugal': '1400-352'}, {'Portugal': '1495-057'}, {'Portugal': '1495-135'}, {'Portugal': '1500-073'}, {'Portugal': '1500-151'}, {'Portugal': '1500-506'}, {'Portugal': '1600-161'}, {'Portugal': '1600-864'}, {'Portugal': '1700-093'}, {'Portugal': '1700-163'}, {'Portugal': '1700-239'}, {'Portugal': '1750-249'}, {'Portugal': '1750-429'}, {'Portugal': '1800-297'}, {'Portugal': '1950-130'}, {'Portugal': '1990-179'}]
but much larger. I want to loop over it, I try like this
for key, value in zip_values:
if key == "France" | key == "Germany" | key == "Spain":
current_zip = check_if_zipcodes_correct(value, 1000, 99999, 5)
check_if_zipcodes_correct is some function that I want to use for zipcodes, but it is not important, I get an error when run the script: ValueError: not enough values to unpack (expected 2, got 1)
CodePudding user response:
You are trying to iterate over a list of dictionaries, for key, value in zip_values
would try to map the key
and value
to a dictionary object(e.g. - {'Spain': '43004'}
) which is not supported. Had it been a list
/tuple
(e.g. [ Spain', '43004']
it would have worked.
Try something like this -
for d in zip_values:
for key, value in d.items():
if key in ("France", "Germany", "Spain"):
current_zip = check_if_zipcodes_correct(value, 1000, 99999, 5)
Additionally, if key == "France" | key == "Germany" | key == "Spain"
can be simplified to if key in ("France", "Germany", "Spain")
CodePudding user response:
Every item in zip_values
is a single 'dict` object , you can't unpack it to two items. You need to iterate over the list and take the first key value pair from each dictionary
for d in zip_values:
key, value = next(iter(d.items()))
# or
key, value = list(d.items())[0]
In addition you can't use |
like this, you need to warppe it with brackets
if (key == "France") | (key == "Germany") | (key == "Spain")
use logical condition
if key == "France" or key == "Germany" or key == "Spain":
or use in
on a list
if key in ["France", "Germany", "Spain"]