简体   繁体   中英

How to get a key in a dictionary in a dictionary

here's my list :

data_config = [{'music': {' extension': 'mp3'}},
 {'reports/INFOB131': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB131'}},
 {'reports/INFOB132': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB132'}},
 {'games': {' name_contains': ['SC2', 'Wesnoth']}},
 {'pictures/Namur': {' extension': 'jpeg',
   ' min_size': '5000000',
   ' name_contains': 'cercle'}},
 {'pictures/autres': {' extension': 'jpeg', ' min_size': '5000000'}}]

When I do these instructions, I get :

for i in data_config[0]['music']:
    print(data_config[0]['music'][i])

output : mp3

But when I do this, I get an error:

print(data_config[0]['music']['extension'])

output : ---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-9-f71c5ad09034> in <module>()
----> 1 print(data_config[0]['music']['extension'])

KeyError: 'extension'

Does anyone have an idea ?

Thank you !

Looks like you have a space in your key name. It's not extension, it's " extension"

In a few places, you have whitespaces. To get rid of them you may want to use .strip() .

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