1

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()
1
  • 1
    Could you add your expected output? Is not clear what do you want to sort. Commented Dec 23, 2018 at 23:40

2 Answers 2

5

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"]), ... ] 
Sign up to request clarification or add additional context in comments.

1 Comment

the other answer was deleted, the link can be removed.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.