0

I have a list with a bunch of dictionaries that I am trying to combine into one

Looks like this...

[{'name':'name', 'value':'john'}, {'name':'sex', 'value':'male'}, {'name':'color', 'value':'blue'}, {'name':'car', 'value':'toyota'}, {'name':'job', 'value':'cashier'}]

I'm trying to combine them all into one dictionary so that the name value is the key and the value is the value. Right now I'm doing something like this and it works fine but I know there is an easier way

keys = []
vals = []

for item in a:
    if item['name']:
        keys.append(item['name'])

    if item['value']:
        vals.append(item['value'])

md = dict(zip(keys,vals))

Any guidance would be appreciated... thank you

  • Perhaps, you can have a look at https://stackoverflow.com/questions/1781571/how-to-concatenate-two-dictionaries-to-create-a-new-one-in-python – dvlper Mar 25 '20 at 02:01
  • Does this answer your question? [How do I merge two dictionaries in a single expression?](https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression) – AMC Mar 25 '20 at 02:37

4 Answers4

5

You can use a dict comprehension.

new = {i['name']:i['value'] for i in a}
xkcdjerry
  • 965
  • 4
  • 15
3

Assuming your list of dictionaries is called dict_list you can use dict comprehension as below:

new_dict = { dict['name'] : dict['value'] for dict in dict_list}
katardin
  • 596
  • 3
  • 14
  • 3
    It's a bad idea to use the names of built-in classes as variable names (dict) in this case it should not matter but it is a bad habit – Iain Shelvington Mar 25 '20 at 01:51
  • 1
    Good comment, I was just trying to make it blindingly obvious what object each step in the comprehension was trying to do (easy to get confused with abstractly named temp variables) – katardin Mar 25 '20 at 01:56
1

You can directly use dict.values() for your specific case as keys and values are available in an order:

dict(d.values() for d in a)
Austin
  • 25,759
  • 4
  • 25
  • 48
0

You can do something like this also.

input_dict_list = [{'name':'name', 'value':'john'}, {'name':'sex', 'value':'male'}, {'name':'color', 'value':'blue'}, {'name':'car', 'value':'toyota'}, {'name':'job', 'value':'cashier'}]

out_put_dict = {}
for input_dict in input_dict_list:
    out_put_dict[input_dict['name']] = input_dict['value']

print(out_put_dict)
krishna
  • 1,029
  • 6
  • 12