Python dictionary with same keys

10,154

Solution 1

How about:

input = [{1: 2}, {2: 2}, {1: 3}, {2: 1}, {1: 3}]

r = {}
for d in input:
    # (assumes just one key/value per dict)
    ((x, y),) = d.items() 
    r.setdefault(x, []).append(y)

print [ {k: v} for (k, v) in r.items() ]

Result:

[{1: [2, 3, 3]}, {2: [2, 1]}]

[update]

just curious : Can you explain whats going on in ((x, y),) = d.items() and r.setdefault(x, []).append(y) ? – damned

First the ((x, y),) = d.items():

  • at this point, d will be an element from input, like {1: 2}
  • d.items() will be something analogous to [(1, 2)]
  • in order to unpack 1 and 2 into x and y, we need the extra , (otherwise the interpreter will think the outer parenthesis are doing grouping instead of defining a single element tuple)

The r.setdefault(x, []).append(y) is analogous to:

if not r.has_key(x):
     r[x] = []
r[x].append(y)

Solution 2

Trick is to use dict.setdefault to start off a list and append to it:

input = [{1: 2}, {2: 2}, {1: 3}, {2: 1}, {1: 3}]
output = {}
for d in input:
    for k,v in d.items():
        output.setdefault(k, []).append(v)

# output contains {1: [2, 3, 3], 2: [2, 1]}

output=[{k:v} for k,v in output.items()]

# output contains [{1: [2, 3, 3]}, {2: [2, 1]}]

What setdefault does is return either the existing list keyed by 'k', or if that key does not exist in the dictionary, it creates a new entry for that key with the second argument and returns that. Either way it returns the list whether it was pre-existing or new, so that you can then append to it.

Share:
10,154

Related videos on Youtube

Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a python list which contains dictionaries and I want to make a new list which contain dictionaries with unique keys and associated list values like below:

    Input:
     [{1: 2}, {2: 2}, {1: 3}, {2: 1}, {1: 3}]
    Output:
     [{1:[2,3,3]},{2:[2,1]}]
    

    Thanks in advance.

  • damned
    damned almost 12 years
    just curious : Can you explain whats going on in ((x, y),) = d.items() and r.setdefault(x, []).append(y) ?
  • octopusgrabbus
    octopusgrabbus almost 12 years
    In your example, what is ls? (for c in ls:).
  • vaidik
    vaidik almost 12 years
    Oh thanks for pointing that out. That was a type. ls is actually output.