-3

How would you go about converting a multi-line dictionary into one dictionary?

For example, the current dictionary, if printed to the screen, is of the form:

{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}

...and so on for over 100 hundred lines. How do you convert this to the following form:

{'keyword':'value','keyword':'value','keyword':'value','keyword':'value'}
wildcard96
  • 105
  • 2
  • 3
  • 9
  • Are you using `'keyword'` as a placeholder, or are you literally trying to combine four dicts with the same contents? – glibdud Nov 13 '17 at 15:36
  • 2
    That isnt a multi line dictionary. Thats 4 seperate dictionaries on 4 seperate lines. Do you mean a list of dictionaries to a singel dictionary?> – Luke.py Nov 13 '17 at 15:37
  • No 'keyword' is just a placeholder. All the keywords are different (all the values are the same). – wildcard96 Nov 13 '17 at 15:37
  • @Luke.py yes well how could you convert the 4 separate dictionaries into ONE dictionary? – wildcard96 Nov 13 '17 at 15:38

3 Answers3

1

Assuming you are asking for multiple dictionaries (not multiple line dictionary) to one dictionary.

a = {1: 1, 2:2}
b = {2:2, 3:3}
c = {2:3}
{**a, **b, **c}

Out: {1: 1, 2: 3, 3: 3}
ExtractTable.com
  • 762
  • 10
  • 20
1

Assuming that your initial data is actually a list of dictionaries and your keys are unique accross all your dictionaries I would use something like -

example = [{'a':1}, {'b':2}, {'c':3}]

objOut = {}
for d in example:
    for k,v in d.iteritems():
        objOut[k] = v

OR

objIn = [{'a':1}, {'b':2}, {'c':3}]

objOut = {}
for d in objIn:
    objOut.update(d)


print objOut
Luke.py
  • 965
  • 8
  • 17
0

Given

dicts = [{'a':1}, {'b':2}, {'c':3, 'd':4}]

Do

{k:v for d in dicts for (k, v) in d.items()}

or

from itertools import chain
dict(chain(*map(dict.items, dicts)))

resulting in

{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119