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?
#1
I have a dictionary:

Quote:rev_sorted_dataDict = dict(sorted(dataDict.items(), reverse = True, key=lambda item: item[1][3]))

The dictionary rev_sorted_dataDict has a student number as key and the value is a list of: [student number, name, class, score] and is sorted according to the score part of the list. The highest score comes first.

groupA, groupB and groupC are empty dictionaries. There are 112 students in all

I need to add the first 37 entries of rev_sorted_dataDict to groupA, the second 37 entries of rev_sorted_dataDict to groupB and the rest (38 students) to groupC.

After that, I will write groupA, groupB and groupC to excel with openpyxl.

With a list I could just append the first 37, but I don't think I can append to a dictionary

What is the best way to populate the dictionaries groupA, groupB and groupC??
Reply
#2
With a list, you can append a new value into the list.

>>> l = [1, 2]
>>> l.append(3)
>>> l
[1, 2, 3]
With a dict, you can add a key/value pair that wasn't there before, or you can update it with another dict, and that either add or changes the values of any matching keys.

>>> d = {'a': 1, 'b': 2}
>>> d['c'] = 3
>>> d.update({'d': 4})
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Reply
#3
From python 3.9 there are also union operators for dicts! - PEP 584 Smile

so this:
d = {'a': 1, 'b': 2}
d.update({'d': 4}
can be also written this way:
d = {'a': 1, 'b': 2}
d |= {'d': 4}
Reply
#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
#5
Update is expecting a sequence, each element of which is a mapping (or a sequence of length 2). So you can't feed it a bare tuple, but you can feed it a list of tuples or a dict created from the tuple.

d = {}
item = ('a', 1)

d.update(item)   # won't work
d.update([item]) # okay
d.update({item}) # also okay
That suggests that since it has to take a sequence anyway, you could create one by slicing your original dict rather than using a for loop.

from itertools import islice

groupA = dict(islice(rev_sorted_dataDict.items(), 0, 38) # or....
groupB = {}
groupB.update(islice(rev_sorted_dataDict.items(), 38, 75)
Pedroski55 likes this post
Reply
#6
Thank you! I had a feeling there must be a better way to do this!

Thanks for showing me!

EDIT AGAIN: NO PROBLEM NOW!

It seems the data is in the dictionary, but I was too stupid to write:

for item in newgroupA.items(): 
>>> newgroupA[2030120109]
[2030120109, '薛璟', '国金(海本)', 102]

but when I do:

for item in newgroupA.items():
print(item)

I only see the student number. Before, I saw the key (student number) and the list (student data)

Still some kind of problem though:

This, with [item] only puts the student number in the groups:

# try with .update
# this only puts the student number in the groups, not good
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
and if I use {item} instead of [item] I get the following error:

Quote:Traceback (most recent call last):
File "<pyshell#155>", line 7, in <module>
groupC.update({item})
TypeError: unhashable type: 'list'

I tried islice:

newgroupA = dict(islice(rev_sorted_dataDict.items(), 0, 38))
but this also only puts the student number in newgroupA

apparently, these methods don't like the list.

The entries in rev_sorted_dataDict all have the format ('student number': ['student number', 'name', 'class', 'score'])

Any ideas why islice can't hack it?? YES, YOU WROTE THE FOR LOOP WRONG, 笨蛋!(bendan means idiot!)

The list is causing the headache I think!

I will use islice, that's much better I think!

Sorry to have bothered you!
Reply


Forum Jump:

User Panel Messages

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