greenafrican
greenafrican

Reputation: 2546

Move data from key to value in Python dictionary

I have a python dict:

{'John': 23, 'Matthew': 8, 'Peter': 45}

I want to create a D3 pie chart and need to move my data from the keys so that I can access the values. So I want to end up with:

[
  {name: 'John', age: 23},
  {name: 'Matthew', age: 8},
  {name: 'Peter', age: 45}
]

How can I do this dynamically (given that I may not know what the current key is, eg. 'John')?

Upvotes: 0

Views: 1045

Answers (1)

sberry
sberry

Reputation: 132018

data = [{"name": key, "age": value} for key, value in my_dict.items()]

An example:

>>> my_dict = {'John': 23, 'Matthew': 8, 'Peter': 45}
>>> data = [{"name": key, "age": value} for key, value in my_dict.items()]
>>> data
[{'age': 8, 'name': 'Matthew'}, {'age': 23, 'name': 'John'}, {'age': 45, 'name': 'Peter'}]

If you are trying to create a javascript friendly representation of the data, then you will need to convert the list of dictionaries to json.

Upvotes: 5

Related Questions