-1

i am facing an issue with Dictionaries in python. When i am printing the dictionary it is giving me output of only one dictionary. Apologies for poor question. as a newbie , i am trying to learn python.

atom1 = {
    'first_name':'Alfa',
    'last_name':'A.',
    'City':'Osaka'
}
atom2 = {
    'first_name':'Beta',
    'last_name':'B.',
    'City':'kyoto'
}
atom3 = {
    'first_name':'Gama',
    'last_name':'G.',
    'City':'L.A.'
}

p = {
    **atom1,**atom2,**atom3
}
print(p)
  • 1
    This is by design. All 3 dicts have the same keys so the last dict "win" – balderman Sep 08 '21 at 14:29
  • 2
    What is your expected output? – balderman Sep 08 '21 at 14:30
  • A `dict` is basically a mapping between keys and values. It assumes the keys are unique (e.g. you can only have one key `first_name`). In your case you are trying to merge 3 dictionaries which have the same keys. This can't be done. What is your expected output? – M. Perier--Dulhoste Sep 08 '21 at 14:31
  • Thanks for the clarification @balderman . I understood it now. My Expected output suppose to be a collection of all 3 dictionaries for example: first_name: alpha last_name:a city:Osaka first_name: beta last_name:b city:kyoto – Sharman00.0 Sep 08 '21 at 14:36

1 Answers1

0

In python a dictionary cannot have duplicated keys. Therefore when you call p = { **atom1, **atom2, **atom3} you assign the value 'Alfa' to the key 'first_name', then later you'll assign 'Gama' to this key.

Which explains why your final dict will have only the last values in front of your keys. For example 'first_name': 'Gama', because 'Beta' and 'Alfa' have been replaced by the last 'first_name'

I suggest you try this: (should work as is)

p = {
    'atom1': atom1,
    'atom2': atom2,
    'atom3': atom3
}
>>> print(p)
{
    'atom1': {'first_name': 'Alfa', 'last_name': 'A.', 'City': 'Osaka'}, 
    'atom2': {'first_name': 'Beta', 'last_name': 'B.', 'City': 'kyoto'}, 
    'atom3': {'first_name': 'Gama', 'last_name': 'G.', 'City': 'L.A.'}
}