-2

If I have two dicts in python

d1={1:2,3:4}
d2={5:6,7:9}

How can I combine that to make

d2 = {{1:2,3:4}, {5:6,7:9}}
David Yuan
  • 810
  • 1
  • 10
  • 15
  • Look into `numpy` (structured arrays, aka record arrays) and use either the `concatenate` or `vstack` function – The Brofessor Aug 04 '15 at 02:15
  • To clarify, do you want to combine into one dictionary (i.e.: `d2 = {1:2,3:4,5:6,7:9}`), or make `d2` a dictionary of two dictionaries? – The Brofessor Aug 04 '15 at 02:21
  • 1
    `d2 = {{1:2,3:4}, {5:6,7:9}}` is not valid Python. Do you mean `d2 = [{1:2,3:4}, {5:6,7:9}]`, `d2 = "{{1:2,3:4}, {5:6,7:9}}"`, `d2 = {9:{1:2,3:4}, 10:{5:6,7:9}}`, what @TheBrofessor said...? – Amadan Aug 04 '15 at 02:21
  • Does `d3=d1,d2` not work? – l'L'l Aug 04 '15 at 02:23

2 Answers2

1

Your request for d2 is not actually a dictionary, but a list. Dictionaries contain key-value pairs. d2 = {{1:2,3:4}, {5:6,7:9}} won't even work I don't think. d2 = [{1:2, 3:4}, {5:6, 7:9}] would likely work, and be easier to pull information from.

Connor
  • 134
  • 6
1

As @Amadan has already suggested, you seem to be wanting a list of two items holding d1 and d2. This can be easily created using the following:

d1 = {1:2,3:4}
d2 = {5:6,7:9}

mylist = [d1, d2]

print mylist

This would display the items as follows:

[{1: 2, 3: 4}, {5: 6, 7: 9}]

You could then iterate through each dictionary as follows:

for d in list_of_d1_d2:
    for k, v in d.items():
        print "{}: {}".format(k,v)
    print

This would display:

1: 2
3: 4

5: 6
7: 9

Tested using Python 2.7

Martin Evans
  • 45,791
  • 17
  • 81
  • 97