-1

i'm having troubles to find a solution to this :

dict_a = {'deecf4bc': 'my_machine'}

dict_b = {'deecf4bc': 'blade-000'}

dict_ab = {'deecf4bc':'my_machine', ' : ', u'blade-000'}

This is a print of my dicts with this :

for key, value in dict_X():
print(key, ' : ', value)

Those dict came from Python libraries like Nova or Ironic I want to create a dict from 2 others based on the first column and I failed hard, I have tried this :

x = dict(a.items() + b.items())

and many more

Someone suggested this : How do I merge two dictionaries in a single expression in Python (taking union of dictionaries)?

It doesn't work as it display the same as dict_b

EDIT : As I was rewriting the dicts, it appears to me that the final form of data that I want is something like one key and 2 values, it it possible ?

Thank you

Sylvain M
  • 1
  • 3
  • 1
    Those aren't dictionaries, but tuples of strings. Are you sure that this is what you have? Can you show the actual code where they are defined? – mkrieger1 Feb 25 '21 at 14:48
  • 1
    `dict_a` is not a `dictionary` but `tuple` – Epsi95 Feb 25 '21 at 14:48
  • To actually merge two actual dicts, see this question: https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python-taking-union-o?rq=1 – Rich Farmbrough Feb 25 '21 at 14:51
  • I have added precisions for this – Sylvain M Feb 25 '21 at 15:07
  • 1
    Sorry, it's actually this: https://stackoverflow.com/questions/20509570/merge-dictionaries-without-overwriting-previous-value-where-value-is-a-list – mkrieger1 Feb 25 '21 at 15:25

2 Answers2

0

To merge dictionnaries:

dict_ab = dict_a | dict_b #Python3.9+

dict_ab = {**dict_a, **dict_b} #Python3.5+
Synthase
  • 5,849
  • 2
  • 12
  • 34
0

looking at your edit note, to group together the values of 2 dict you can do the following

>>> a={i:i*10 for i in range(5)}
>>> b={i:i*100 for i in range(5)}
>>> a
{0: 0, 1: 10, 2: 20, 3: 30, 4: 40}
>>> b
{0: 0, 1: 100, 2: 200, 3: 300, 4: 400}
>>> from collections import defaultdict
>>> c=defaultdict(list)
>>> for d in [a,b]:
        for k,v in d.iteritems(): #d.items() in py3+
            c[k].append(v)

        
>>> c
defaultdict(<class 'list'>, {0: [0, 0], 1: [10, 100], 2: [20, 200], 3: [30, 300], 4: [40, 400]})
>>> 
Copperfield
  • 8,131
  • 3
  • 23
  • 29