0

I have a dictionary of dictionaries that looks like this:

{'info': {'status': 'OK',
          'data': {'account': [{'currency': 'USD',
                                'name': 'United States Dollar',
                                'amount': '100',
                                'used': '20',
                                'total': '120'},
                               {'currency': 'EUR',
                                'name': 'Euro',
                                'amount': '150',
                                'used': '35',
                                'total': '185'}]}},
 'USD': {'amount': 100, 'used': 20, 'total': 120},
 'EUR': {'amount': 150, 'used': 35, 'total': 185},
 'amount': {'USD': 100, 'EUR': 150},
 'used': {'USD': 20, 'EUR': 35},
 'total': {'USD': 120, 'EUR': 185}}

What I want to get from this is a currency list:

currency_list = ['USD','EUR']

and I would like to get a currency name list:

currency_list = ['United States Dollar','Euro']

How can I access the dictionaries?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
MathMan 99
  • 665
  • 1
  • 7
  • 19
  • First off you should consider a different approach to building that dictionary. But You could do something like [curr["currency"] for curr in your_dict["info"] ["data"] ["accounts"]]. That should give the result you are expecting. I haven't tried it so it might need a little work – M. Villanueva Feb 10 '22 at 22:37
  • Are you looking for a recursive solution or are you asking how to access dicts in general? Do you want to build a pandas DataFrame object (since you tagged this pandas)? What is the question? –  Feb 10 '22 at 22:53
  • There's redundancy in the data. The keys in the outer dictionary have info that's already available under `info`. – Mark Tolonen Feb 11 '22 at 00:53

3 Answers3

2

given that this info you posted in a var dic just do:

currency_list = [value["currency"] for value in dic["info"]["data"]["account"]]

currency_list_name = [value["name"] for value in dic["info"]["data"]["account"]]

Igor Vaz
  • 36
  • 2
0

You can access a dictionary of dictionaries by calling the dictionary with both keys you need to use. For example currency_list[info][status] would return 'OK'. The way you have your dictionary set up is a bit confusing. I might restructure it in order to access each element in simpler fashion.

glibsy
  • 1
  • 1
0

If your dictionary is saved in a variable named yourdictionary you can use the following code.

data = yourdictionary['info'].get('data').get('account')

currency_list = [dat['currency'] for dat in data] 
currency_name_list = [dat['name'] for dat in data]

Here list comprehension is used to locate all currencies and names in the dictionary.