P
P
pivazik2020-06-19 23:05:16
Python
pivazik, 2020-06-19 23:05:16

How to move a dictionary to another dictionary?

How can I move all dictionary values ​​to another (new) dictionary.

1 = {1: "один", 2: "два"}
2 = {}
#код...
2 = {1: "один", 2: "два"}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
StudMG, 2020-06-19
@pivazik

There are 2 ways.
If there is a need to simply copy the values ​​of one dictionary from another, simply assigning one name to another will not work.

dict1 = {1: "один", 2: "два"}
dict2 = dict1  # Так делать НЕЛЬЗЯ!

This will simply pass a reference to the first dictionary object and any changes to the second will change the first dictionary in the same way. In fact, you just rename it.
It is done like this:
dict1 = {1: "один", 2: "два"}
dict2 = dict1.copy()  # Так делать ПРАВИЛЬНО!

Here we create a copy of the dictionary and give the object the name dict2.
The second way:
If you need to somehow process the values ​​​​that we transfer to another dictionary, you can use iteration:
dict1 = {1: "один", 2: "два"}
dict2 = {}
for key in dict1:
    dict2[key] = dict1[key]

Or another way to loop:
dict1 = {1: "один", 2: "два"}
dict2 = {}
for key, item in dict1.items():
    dict2[key] = item

Then we can somehow process our values ​​​​that we assign to a new dictionary right at the time of recording, for example, multiply
dict1 = {1: "один", 2: "два"}
dict2 = {}
for keys in dict1:
    dict2[keys] = dict1[keys] * 2

E
EzikBro, 2020-06-19
@EzikBro

Dictionaries have an update method that adds new values ​​to the dictionary and overwrites old ones:

dict1 = {1: 'one', 2: 'two'}
dict2 = {3: 'three'}
dict2.update(dict1)
dict2
>> {3: 'three', 1: 'one', 2: 'two'}

a = {1: 111, 2: 222, 3: 333}
b = {1: 444, 2: 555, 4: 666, 5: 777}
b.update(a)
b
>> {1: 111, 2: 222, 4: 666, 5: 777, 3: 333}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question