-1

super beginner at python here.

I'm trying to convert a list of dictionaries into a single dictionary.

So, something like this:

[ {'Name': 'JD', 'Number': 1}, 
  {'Name': 'Turk', 'Number': 2}, 
  {'Name': 'Carla', 'Number': 3}], 

I'd like to change it into

{'Name': 'JD', 'Number': 1, 
 'Name': 'Turk', 'Number': 2, 
 'Name': 'Carla', 'Number': 3}

I've been trying this for a while and have looked at a bunch of answers here, but it isn't working.

Thank you!

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • 5
    short answer: you can't, without blowing up the majority of your data. Keys are unique. – roippi Feb 09 '14 at 05:04
  • He can use the index as a key. – jeremyjjbrown Feb 09 '14 at 05:05
  • 1
    Your expected output is not possible as dictionary key are unique. – James Sapam Feb 09 '14 at 05:07
  • Dict use hashing to index on key So two keys can be with same values and dict keys are unique. I believe your present data-structure is correct. What algo/operation you need apply on this list of dict? – Grijesh Chauhan Feb 09 '14 at 05:10
  • I just changed my code and used something else. It worked out! Thanks guys. Should I just delete this post or? – user3288886 Feb 09 '14 at 05:19
  • possible duplicate of [List of dictionaries, in a dictionary - in Python](http://stackoverflow.com/questions/1889385/list-of-dictionaries-in-a-dictionary-in-python) – Maz I Feb 09 '14 at 05:20

1 Answers1

1

No, you can't do this. As roippi said, Keys are unique

Try this instead:

>>> from collections import defaultdict
>>> new_dict = defaultdict(list)
>>> for d in li:
    for k, v in d.items():
        new_dict[k].append(v)

>>> new_dict
defaultdict(<class 'list'>, {'Number': [1, 2, 3], 'Name': ['JD', 'Turk', 'Carla']})
laike9m
  • 18,344
  • 20
  • 107
  • 140