Hamperfait
Hamperfait

Reputation: 515

Update a dict values with values in a list

I have a dictionary I want to update:

my_dict = {"a":"A", "b":"B"}

and a list with the exact same length:

my_list = ["D", "E"]

I would like to find the most efficient way to update my_dict with the values from my_list to:

{"a":"D", "b":"E"}

without having to run multiple for loops or similar. I tried to do this with list comprehensions, but it does not allow multiple statements:

{my_dict_key:list_item for my_dict_key in my_dict.keys(), list_item in my_list}

Upvotes: 1

Views: 697

Answers (3)

Austin
Austin

Reputation: 26039

Use zip() with a dictionary-comprehension:

{key: value for key, value in zip(my_dict, my_list)}

Or just:

dict(zip(my_dict, my_list))

Upvotes: 7

sai Pavan Kumar
sai Pavan Kumar

Reputation: 1177

May be it will help

  1. First find keys by
    keys=dic.keys()
  1. Then Update your dictionary with list elements
    for i in range(len(lis)):
        dic[keys[i]]=lis[i] 

3.The Dictionary will be updated.

Upvotes: -1

Nick Reed
Nick Reed

Reputation: 5059

If you know the order of your dict is the same as the list, you can use a ranged for loop to go through each key.

for i, key in enumerate(dic):
  dic[key] = lis[i]

Demo

Upvotes: 0

Related Questions