Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy one key pair value from one dictionary to another in python [duplicate]

Lets say I have a dictionary:

mydict = {"color":"green",
          "type":"veg",
          "fruit":"apple",
          "level": 5
          }
new_dict = {}

I would like to append the key "color" and "fruit" and their values receptively into the new_dict. what is the easiest way to do that? Thank you.

like image 341
jimrahman Avatar asked Oct 15 '25 15:10

jimrahman


2 Answers

You can try this:

new_dict = {x:mydict[x] for x in mydict if x in ('color','fruit')}
like image 178
Sho_Lee Avatar answered Oct 17 '25 11:10

Sho_Lee


the easiest way is this:

new_dict["color"] = mydict["color"]

however, if you had a larger list of items you need to pass to a new dict, you could use the following:

items = ["color", "fruit"]
for item in items:
    new_dict[item] = mydict[item]
like image 26
Charles Carriere Avatar answered Oct 17 '25 12:10

Charles Carriere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!