d[key] = value
but how to get the keys from value?
For example:
a = {"horse": 4, "hot": 10, "hangover": 1, "hugs": 10}
b = 10
print(do_something with 10 to get ["hot", "hugs"])
Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.
Use a list in a dictionary to associate more than one value with a key. Create a dictionary with lists as values. Use a list to contain more than one value. Though the key isn't duplicated, multiple values are now assigned to the same key.
Method 1: Get the key by value using list comprehension. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list to get the key from a value in Dictionary.
Method 1 : Using List. Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.
You can write a list comprehension to pull out the matching keys.
print([k for k,v in a.items() if v == b])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With