Abo
Abo

Reputation: 69

Assign dictionary value from another dictionary value

I get lost in the peace of code. I have two dictionaries as below, and I want to replace the values of vigitables dictionary by the values of the fruits dictionary.

fruits = {'Apples':2,'Oranges':4,'Bananas':6}

vigitables = {'Tomatos':3,'Potatos':5,'Onions':7}

i tried this

for k in vigitables.keys():

vigitables[k] = fruits.values()

but it gave me None.

the expecting output

vigitables = {'Tomatos':2,'Potatos':4,'Onions':6}

Thank you in advance

Upvotes: 2

Views: 2082

Answers (2)

U13-Forward
U13-Forward

Reputation: 71610

Try this dict(zip(...)) command:

print(dict(zip(vigitables.keys(), fruits.values())))

For a loop command:

d = {}
for x, y in zip(vigitables.keys(), fruits.values()):
    d.update({x: y})

For loop solution without zip:

d = {}
keys = list(vigitables.keys())
values = list(fruits.values())
for i in range(len(keys)):
    d.update({keys[i]: values[i]})

They all output:

{'Tomatos': 2, 'Potatos': 4, 'Onions': 6}

Upvotes: 2

Austin
Austin

Reputation: 26037

Similar to other answer, but more concise. When you use vigitables, you take only its keys.

dict(zip(vigitables, fruits.values()))

Example:

fruits = {'Apples':2,'Oranges':4,'Bananas':6}

vigitables = {'Tomatos':3,'Potatos':5,'Onions':7}  
print(dict(zip(vigitables, fruits.values())))

# {'Tomatos': 2, 'Potatos': 4, 'Onions': 6}

zip() creates a tuple of key and value from the two dictionaries and a dict() on it creates dictionary.

Upvotes: 0

Related Questions