xxxxxxxxxx
d = {'key1': 'aaa', 'key2': 'aaa', 'key3': 'bbb'}
keys = [k for k, v in d.items() if v == 'aaa']
print(keys)
# ['key1', 'key2']
keys = [k for k, v in d.items() if v == 'bbb']
print(keys)
# ['key3']
keys = [k for k, v in d.items() if v == 'xxx']
print(keys)
# []
xxxxxxxxxx
myDict = {
"message": "Hello Grepper!"
}
for key, value in myDict.items():
print(key) #Output: message
print(value) #Output: Hello Grepper!
xxxxxxxxxx
# creating a new dictionary
my_dict ={"java":100, "python":112, "c":11}
# list out keys and values separately
key_list = list(my_dict.keys())
val_list = list(my_dict.values())
# print key with val 100
position = val_list.index(100)
print(key_list[position]
output: java
xxxxxxxxxx
dict = {1: 'a', 2: 'b'}
value = 'a'
key = [x for x in dict.keys() if dict[x] == value][0]
xxxxxxxxxx
# creating a new dictionary
my_dict ={"Java":100, "Python":112, "C":11}
# one-liner
print("One line Code Key value: ", list(my_dict.keys())
[list(my_dict.values()).index(100)])
xxxxxxxxxx
print(d.get('key5', 'NO KEY'))
# NO KEY
print(d.get('key5', 100))
# 100