Jed
0
Q:

python dictionary find key by value

# 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')
0
def method1(list,search_age):
	for name,age in list.iteritems():
		if age == search_age:
			return name
# Python 3
def method2(list,search_age):
	return [name for name,age in list.items() if age == search_age]

def method3(list,search_age):
	return list.keys()[list.values().index(search_age)]
1
print(list(d.keys())[list(d.values()).index(990)])
-3

New to Communities?

Join the community