Python Forum
What is the best way to add entries from 1 dictionary to another?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What is the best way to add entries from 1 dictionary to another?
#4
Thanks for the replies!

This is what I did yesterday. It worked, but is perhaps not so elegant.

groupA = {}
groupB = {}
groupC = {}

# this works
count = 1
for key in rev_sorted_dataDict.keys():    
    if count < 38:
        groupA[key] = rev_sorted_dataDict[key]
    elif count > 37 and count < 75:
        groupB[key] = rev_sorted_dataDict[key]
    elif count > 74:
        groupC[key] = rev_sorted_dataDict[key]
    count += 1
I just tried with .update, but I get an error.

Starting from rev_sorted_dataDict, a key looks like this:

Quote:2030120109 (just a student number)

and an rev_sorted_dataDict item (key: value pair) looks like this:

Quote:(2030070218, [2030070218, '王健康', '会计(海本2)', 58]) from which the value is the list

but apparently .update doesn't like this. How should I implement this with update?

From the idle shell:

for item in rev_sorted_dataDict.items():    
    if count < 38:
        groupA.update(item)
    elif count > 37 and count < 75:
        groupB.update(item)
    elif count > 74:
        groupC.update(item)
    count += 1

Quote:Traceback (most recent call last):
File "<pyshell#144>", line 3, in <module>
groupA.update(item)
TypeError: cannot convert dictionary update sequence element #0 to a sequence
Reply


Messages In This Thread
RE: What is the best way to add entries from 1 dictionary to another? - by Pedroski55 - Oct-20-2020, 11:33 PM

Forum Jump:

User Panel Messages

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