Python Forum
Copy item from one dict to another
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Copy item from one dict to another
#1
Hello,
Does exist a method of copying an items from one dict to another, e.g. inside a for loop, under specific conditions ?
I tried
for item in dict1.items():
if {condition}:
dict2.update(item)
Doesn't work.
Thanks
Reply
#2
Resolved: item in update should be in curly brackets
for item in dict1.items():
if {condition}:
dict2.update({item})
Reply
#3
You can use a dictionary comprehension.
d1 = {'A': 1, 'B': 3}
d2 = {'C': 4, 'D': 5, 'E': 6, 'F':7}
d1.update({key: value for key, value in d2.items() if value % 2})
print(d1)
Output:
{'A': 1, 'B': 3, 'D': 5, 'F': 7}
In response to your second post, curly brackets (set) are probably not the correct choice. You could use square brackets (list) or round brackets (tuple). The important thing is that the argument is iterable object with key value pairs.
d1 = {'A': 1, 'B': 3}
d2 = {'C': 4, 'D': 5, 'E': 6, 'F':7}
d1.update((item for item in d2.items() if item[1] % 2))
print(d1)
Output:
{'A': 1, 'B': 3, 'D': 5, 'F': 7}
Reply
#4
Thanks,
Anyway, the code pattern in my 1st post is irrelevant because in the condition the item's value is checked.
So the loop should run on (key, value) rather than on items.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why is the copy method name in python list copy and not `__copy__`? YouHoGeon 2 286 Apr-04-2024, 01:18 AM
Last Post: YouHoGeon
  Remove an item from a list contained in another item in python CompleteNewb 19 5,781 Nov-11-2021, 06:43 AM
Last Post: Gribouillis
  Sort a dict in dict cherry_cherry 4 75,728 Apr-08-2020, 12:25 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020