Home > Back-end >  Call values of keys in dictionary through function
Call values of keys in dictionary through function

Time:09-27

I have following list:

cosmetics = {"Hair": ["Shampoo", "Conditioner", "Repair"], "Skin": ["Cream", "Lotion", "Wipes"], "MakeUp": ["Lipstick", "Foundation", "Liner"]}

print(cosmetics.get("Hair"))
print(cosmetics.get("Skin"))
print(cosmetics.get("MakeUp"))

1. def care(cosmetics):
    x = cosmetics.keys()
    for x in cosmetics:
        print(cosmetics.get(x))

print(care("Skin"))

2. def care(key, value):
    print(key, value)
[care(key, value) for key,value in cosmetics.items()]

Get an error here:

def care(key):  
for key,value in cosmetics.items(): 
print(key, value)

So, my problem is I get the whole dictionary with these functions. I want to create a function care so when I call 'care' with a key like skin, I get the values of that key.

CodePudding user response:

Try this:

>>> dct = cosmetics = {"Hair": ["Shampoo", "Conditioner", "Repair"], "Skin": ["Cream", "Lotion", "Wipes"], "MakeUp": ["Lipstick", "Foundation", "Liner"]}
>>> def get_val_dct(dct, key):
...    return dct.get(key)

>>> get_val_dct(dct,'Skin')
['Cream', 'Lotion', 'Wipes']
  • Related