Reputation: 11
How do I append two values to a key in dictionary
It is throwing error str object has no attribute append
score_list={}
for _ in range(int(input())):
score=float(input())
name=input()
if score in score_list:
score_list[score].append(name)
else:
score_list[score]=name
new_list=[]
for score in score_list:
new_list.append([score,score_list[score]])
new_list.sort()
Upvotes: 1
Views: 108
Reputation: 51643
You need to add a list
to your dict - not the string directly. Three ways I know of, from worst to best.
You can either use a normal dict and change your code to
score_list={} for _ in range(int(input())): score=float(input()) name=input() if score in score_list: score_list[score].append(name) else:
score_list[score] = [name] # add as 1-elem list
or use dict.setdefault(key,defaultvalue)
:
score_list={} for _ in range(int(input())): score=float(input()) name=input()
k = score_list.setdefault(score,[]) # create key if needed with empty list
k.append(name)
or use a collections.defaultdict(list)
.
score_list=defaultdict(list)
for _ in range(int(input())): score=float(input()) name=input()
score_list[score].append(name) # defaultdict handles list creation for you
The last method is most performant - setdefault(score,[])
creates lots of empty default-lists that are not used if the key already exists.
If you need a top n result, you can create it directly from the dictionaries item()s:
n = 5
top_n = sorted(score_list.items(), reverse=True) [:n] # sorts by max score first
# top_n is a list of tuples: [ (10000,["a","b","c"]) , (9999, ["b"]), ... ]
Upvotes: 5
Reputation: 61910
If I understood correctly, you need to change the line:
score_list[score]=name
to:
score_list[score]=[name]
In your current version you are assigning the string name
to score_list[score]
, so you need to change to a list hence the change.
Upvotes: 2