Home > Net >  Copying info from one dictionary into a new one
Copying info from one dictionary into a new one

Time:03-20

I am new to python and to dictionaries so this may be a basic question but I have one dictionary that has strings as keys and integers as values. I want to create a new dictionary with the same keys from the previous dictionary but adjust the integers (multiply them but a number).

CodePudding user response:

The simplest way is a comprehension over the items() of the existing dictionary:

>>> d = {"a": 1, "b": 2, "c": 3}
>>> {k: v * 3 for k, v in d.items()}
{'a': 3, 'b': 6, 'c': 9}

CodePudding user response:

Multiple solutions are possible.

Copy and update

dict_a = {
    "a": 2,
    "b": 3,
}

# copy
dict_b = dict_a.copy()
# or
# dict_b = dict(dict_a)

# update values
for key in dict_b.keys():
    dict_b[key] *= dict_b[key]

Dictionary comprehension

dict_a = {
    "a": 2,
    "b": 3,
}

dict_b = {key: value * value for key, value in dict_a.items()}

CodePudding user response:

Based on an already asked question, you can use the update dictionary method. It is also a one-liner clean and clear solution. for example:

d = {"a": 1, "b": 2, "c": 3}
d.update((x, y*3) for x, y in d.items())
print(d)

outputs:

{'a': 3, 'b': 6, 'c': 9}
  • Related