简体   繁体   中英

Accessing nested dictionary in Python 3.5

I'm importing a nested dictionary from an external file and trying to access values in the deepest level; however, when I try to use for loops I get the following error:

print(country['unicode'])
TypeError: string indices must be integers

The dictionary I'm importing (from a file emojiFlags.py ) looks like this:

flagSet = {'emojiFlagSet': {'Andorra': {'emoji': '🇦🇩', 'unicode': 
'U+1F1E6 U+1F1E9'}, 'Afghanistan': {'emoji': '🇦🇫', 'unicode': 'U+1F1E6 
U+1F1EB'}, ... }}

etc. etc.

Here are the snippets of code I'm working with:

from emojiFlags import flagSet

# Get country emoji data
for country in flagSet['emojiFlagSet']:
    print(country['unicode'])

I'm fairly certain I've done something like this on a number of other dictionaries before (and had no problems), and I'm wondering if there's something obvious I'm missing at this point.

Oddly, if I print(flagSet) , my return is emojiFlagSet (the key), not its value (a dictionary); however, if I print(flagSet['emojiFlagSet']) the return is the entire nested dictionary value as it should be. If I instead try

for country in flagSet['emojiFlagSet']:
    print(country)

I get all of the country names, but, just like with the print(flagSet) statement, I only get the keys and not their nested dictionary values.

My end goal is to simply return the value of the 'unicode' keys within each country's dictionary. So, I'd expect to see

U+1F1E6 U+1F1E9

for the first country, for example.

Strangest of all, if I do

print(flagSet['emojiFlagSet']['Andorra']['unicode'])

as a simple test, I get exactly what I'm looking for. Any suggestions on where I'm going wrong in my for loop?

You are iterating over the dictionary itself, which yields the keys for that dictionary. In your flagSet['emojiFlagSet'] dictionary, those keys are strings (such as 'Andorra' and 'Afghanistan' ).

You wanted the values instead, it is the values that are dictionaries too. Loop over dict.values() :

for country in flagSet['emojiFlagSet'].values():
    print(country['unicode'])

Note that the fact that you imported the datastructure from another module has no bearing on all of this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM