I am attempting to find the value of a particular key from within a dictionary that is itself within a list, and then print that value.
iso3166_1 = [
{
"name_en": "Afghanistan",
"name_fr": "Afghanistan (l')",
"full_name": "the Islamic Republic of Afghanistan",
"alpha2": "AF",
"alpha3": "AFG",
"numeric": "004",
"independent": "Yes"
},
{
"name_en": "Ă…land Islands",
"name_fr": "Ă…land(les ĂŽles)",
"full_name": "N/A",
"alpha2": "AX",
"alpha3": "ALA",
"numeric": "248",
"independent": "No"
},
{
"name_en": "Albania",
"name_fr": "Albanie (l')",
"full_name": "the Republic of Albania",
"alpha2": "AL",
"alpha3": "ALB",
"numeric": "008",
"independent": "Yes"
}
]
print("Are you looking for an existing country, subdivision, or former country? Type 1, 2, or 3 for that option.")
user_input = input()
if user_input == "1":
print("Enter the name or code of a country.")
lookup = str.lower(input())
if lookup == "N/A":
print("'N/A' is present in too many entries to list.")
else:
for entry in iso3166_1:
for i in entry:
if lookup == i:
found_lookup = True
dict = iso3166_1.index(entry)
name_en = iso3166_1[iso3166_1.index(entry)]["name_en"]
print(f"Short-form English name: {name_en}")
else:
print("Not found.")
The problem is that it fails to find the dictionary and prints Not found. regardless of what is inputted by the user.
The aforementioned problem is everything under the for loop starting at for entry in iso3166_1:, but a small section of the list of dictionaries is included for context.
>Solution :
In your inner loop, try looping over the values in the entry dictionary, e.g.,
if user_input == "1":
print("Enter the name or code of a country.")
found_lookup = False
lookup = str.lower(input())
if lookup == "N/A":
print("'N/A' is present in too many entries to list.")
else:
for entry in iso3166_1:
# loop over values in entry dictionary
for i in entry.values():
# compare values to the input
if lookup == i.lower():
found_lookup = True
# get the short form English name from entry
name_en = entry["name_en"]
print(f"Short-form English name: {name_en}")
break
else:
# break out the loop
if found_lookup:
break
if not found_lookup:
print("Not found")