Nick
Nick

Reputation: 97

Searching for value in dictionary and return a new dictionary with the corresponding key and value

So lets say I have this dictionary of preschool kids. The key is the names and the values represent : favorite color, age, and hair color.

    preschool_kids={"Suzie":("purple", 4, "brown"), 
"Michael":("blue", 3, "blond"), "Jane":("purple",5, "black")}

So I'm testing to see which of these student's favorite color is purple, and wanting the following output:

{"Suzie":("purple", 4, "brown"),"Jane":("purple",5, "black")}

I've done the following (using dictionary above)trying to get that result:

def search(values, color):
    d={}
    for key,value in preschool_kids.items():
        colors=value[0]

        if color in colors:
            d= (key, value)
            print(d)

print (search(preschool_kids, "purple")) 

but instead I keep coming out with :

('Suzie', ('purple', 4, 'brown'))
('Jane', ('purple', 5, 'black'))

How can I get it to form a new dictionary with the search results from my code instead of a tuple? It definitely seems to be giving me the right things I'm asking for, but just not in the output I want.

Also, since I'm quite new to Python, I'd rather not import things, since I don't have much experience or full understanding of the different imported libraries.

Upvotes: 1

Views: 65

Answers (2)

Akshat Mahajan
Akshat Mahajan

Reputation: 9846

The Problem

d = (key,value) is the wrong way to assign a key to a value in a dictionary. This creates a tuple (key,value) and assigns it to d, overwriting its previous existence as a dictionary.

The Best Solution

Use a dictionary comprehension. This is the smart way:

result = {k: v for k,v in preschool_kids.items() if v[0] == color}

This creates a new dictionary with only the results you want.

The Naive Solution (and the right way to assign in dictionaries)

The naive way to do it is:

d={}
for key,value in preschool_kids.items():
    if value[0] == color:
        d[key] = value # right way to assign a value to a key
print(d) # this prints the entire dictionary, and not the dictionary at each step

Upvotes: 1

Serdmanczyk
Serdmanczyk

Reputation: 1224

You're close! You just need to update the dictionary you're building in your function to map the student's name to their attributes and return it:

preschool_kids = {
    "Suzie": ("purple", 4, "brown"),
    "Michael": ("blue", 3, "blond"), "Jane":("purple",5, "black")
}

def search(values, color):
    students_with_favorite_color = {}
    for name,attrs in preschool_kids.items():
        students_favorite_color = attrs[0]

        if students_favorite_color == color:
            students_with_favorite_color[name] = attrs

    return students_with_favorite_color

print(search(preschool_kids, 'purple'))

Upvotes: 0

Related Questions