David
David

Reputation: 459

creating a function that takes the key and value of a dictionary to create a new value

I'm trying to come up with a simple function that takes two inputs (dict key and dict value) and returns a new value for the dictionary. And I want it to be able to be called for a broad number of cases, not just one specific instance.

sample input would look like this:

dict = {1: 11, 2: 12, 3: 13, 4: 14, 5: 15}

and the output would look like this:

new_dict = {1: 12, 2: 14, 3: 16, 4: 18, 5: 20}

I was trying to use something like a dict comprehension (new_dict = {k:v + k, v in dict.items()}, which obviously does not work), but not sure if this is the right approach and couldn't figure out how to get that addition part to work correctly. What's a clean/simple way of going about this to be able to work with a bunch of different inputs?

Upvotes: 0

Views: 70

Answers (3)

Ilija
Ilija

Reputation: 1604

First, dict is already used for instantiating dictionaries, and you shouldn't use it in the manner you did.

Second, you are missing important part in comprehension and that is for.

That's why it didn't work.

Heres how it works:

a = {1: 11, 2: 12, 3: 13, 4: 14, 5: 15}

print {k: k+v for k, v in a.items()}
# {1: 12, 2: 14, 3: 16, 4: 18, 5: 20}

Upvotes: 0

George J Padayatti
George J Padayatti

Reputation: 898

You could do something like this:

for i in dict:
    new_dict[i] = dict[i] + i

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599638

You're just missing the for in your list comprehension.

new_dict = {k:v + k for k, v in dict.items()}

Upvotes: 7

Related Questions