简体   繁体   中英

How to extract the value of a specific key, and add it to a variable using Python?

I have a site that takes an userinput eg USD and requests data from an API to get exchange rates. I assign to a variable, var = {'rates': {'DKK': 7.4618}, 'base': 'EUR', 'date': '2020-05-06'} and want to extract only the specific key (DKK) and it's value to their own variable.

If your data format is the same as above then you can access in the following way.

DKK = var.get("rates", {}).get('DKK')

You can access a dictionaries value by passing the key to the dict.

value = var['rates']['DKK']

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