简体   繁体   中英

Dictionary of lists and list of tuples comparison

So I am trying to get my dictionary of lists to match up with my list of tuples. (hopefully that makes sense). I have a dictionary with lists as the values, my values are individual scores for each book, ex: the value 5 on bob would equal the first book in the book list, :

d = {'bob':[5,0,0,1,3], 'toms':[3,0,5,3,0], 'sammy': [0,0,0,1,0], 'ted':[5,0,0,6,3]}

and a list of tuples:

books=[('Douglas Adams', "The Hitchhiker"), ('Richard Adams', 'Watership'), ('Mitch Albom', 'The Five People'), ('Laurie Anderson', 'Speak'), ('Maya Angelou', 'Caged Bird Sings')]

So what I would like is to be able to be able to some how say when someone has a value of 3 or 6 I can pull them out to say what books have those ratings. Thanks!

Edit: I would like it to output a dictionary of some sort where it would say:

selectScores = {bob: ('Maya Angelou', 'Caged Bird Sings'), toms: (Maya Angelou', 'Caged Bird Sings', Laurie Anderson', 'Speak')} 

and so on for each person

something like that I would hope to be the output.

You can try something like this. Basically enumerate the dictionary values and use it's index to access the books array.

d = {'bob':[5,0,0,1,3], 'toms':[3,0,5,3,0], 'sammy': [0,0,0,1,0], 'ted':[5,0,0,6,3]}
books=[('Douglas Adams', "The Hitchhiker"), ('Richard Adams', 'Watership'), ('Mitch Albom', 'The Five People'), ('Laurie Anderson', 'Speak'), ('Maya Angelou', 'Caged Bird Sings')]

select_scores = {}
for key, books_scores in d.items():
    for i, score in enumerate(books_scores):
        if score == 3 or score == 6:
            if key not in select_scores:
                select_scores[key] = []
            select_scores[key].append(books[i])
            
print(select_scores)

Output:

{'bob': [('Maya Angelou', 'Caged Bird Sings')], 'toms': [('Douglas Adams', 'The Hitchhiker'), ('Laurie Anderson', 'Speak')], 'ted': [('Laurie Anderson', 'Speak'), ('Maya Angelou', 'Caged Bird Sings')]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM