Home > database >  To reconstruct and change it to a form of one dictionary rather than two dictionaries
To reconstruct and change it to a form of one dictionary rather than two dictionaries

Time:11-19

I have the dictionary below:

dict_ex = {
        "coffee": "3",
        "milk": "7",
        "list": {
            "cola": "2",
            "juice": "1"
        }
    }

I would like to reconstruct it and change it to a form of one dictionary rather than two dictionaries:

dict_ex = {
     "coffee": "3",
     "milk": "7",
     "cola": "2",
     "juice": "1"
     }

I've revised this, so please check if this is right.. I would appreciate it if you could give me even a little advice.

CodePudding user response:

Update the original dictionary with the contents of the value of list:

>>> dict_ex.update(dict_ex["list"])

Then delete the list key from the dictionary:

>>> del dict_ex["list"]

Result:

>>> dict_ex
{'coffee': '3', 'milk': '7', 'cola': '2', 'juice': '1'}

CodePudding user response:

You can use dict.update with dict.pop

  • dict.update(other) from Docs:

    Update the dictionary with the key/value pairs from other, overwriting existing keys.

  • dict.pop(key) from Docs:

    If key is in the dictionary, remove it and return its value.

dict_ex.update(dict_ex.pop('list'))
print(dict_ex)
# {'coffee': '3', 'milk': '7', 'cola': '2', 'juice': '1'}

As an aside, if you don't want to update the original dict. We can use dict comp with union1 shorthand.

Python >= 3.9

out = {k: dict_ex[k] for k in dict_ex.keys()-['list']} | dict_ex['list']

Python <= 3.8

There's are SO posts Retain all entries except for one key python and How do I merge two dictionaries in a single expression (take union of dictionaries)?

out = { **{k: dict_ex[k] for k in dict_ex.keys()-['list']}, **dict_ex['list'] }

  1. From Docs
  • d | other

    Create a new dictionary with the merged keys and values of d and other, which must both be dictionaries. The values of other take priority when d and other share keys. New in version 3.9.

  • Related