how to get the key for a value in a dictionary in python
# Python program to show working
# of keys in Dictionary
# Dictionary with three keys
Dictionary1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
# Printing keys of dictionary
print(Dictionary1.keys())
# Creating empty Dictionary
empty_Dict1 = {}
# Printing keys of Empty Dictionary
print(empty_Dict1.keys())
# 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_list[val_list.index(100)])
print(key_list[val_list.index(112)])
# one-liner
print(list(my_dict.keys())[list(my_dict.values()).index(112)])
## Values need to be unique
# 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_list[val_list.index(100)])
print(key_list[val_list.index(112)])
# one-liner
print(list(my_dict.keys())[list(my_dict.values()).index(112)])
# Create a list of dictionary
datadict = [{'Name': 'John', 'Age': 38, 'City': 'Boston'},
{'Name': 'Sara', 'Age': 47, 'City': 'Charlotte'},
{'Name': 'Peter', 'Age': 63, 'City': 'London'},
{'Name': 'Cecilia', 'Age': 28, 'City': 'Memphis'}]
# Build a function to access to list of dictionary
def getDictVal(listofdic, name, retrieve):
for item in listofdic:
if item.get('Name')==name:
return item.get(retrieve)
# Use the 'getDictVal' to read the data item
getDictVal(datadict, 'Sara', 'City') # Return 'Charlotte'
# -------------------
# to convert a dataframe to data dictionary
df = pd.DataFrame({'Name': ['John', 'Sara','Peter','Cecilia'],
'Age': [38, 47,63,28],
'City':['Boston', 'Charlotte','London','Memphis']})
datadict = df.to_dict('records')