Answers for "how to get a value from a dictionary python"

109

python dictionary

#Creating dictionaries
dict1 = {'color': 'blue', 'shape': 'square', 'volume':40}
dict2 = {'color': 'red', 'edges': 4, 'perimeter':15}

#Creating new pairs and updating old ones
dict1['area'] = 25 #{'color': 'blue', 'shape': 'square', 'volume': 40, 'area': 25}
dict2['perimeter'] = 20 #{'color': 'red', 'edges': 4, 'perimeter': 20}

#Accessing values through keys
print(dict1['shape'])

#You can also use get, which doesn't cause an exception when the key is not found
dict1.get('false_key') #returns None
dict1.get('false_key', "key not found") #returns the custom message that you wrote 

#Deleting pairs
dict1.pop('volume')

#Merging two dictionaries
dict1.update(dict2) #if a key exists in both, it takes the value of the second dict
dict1 #{'color': 'red', 'shape': 'square', 'area': 25, 'edges': 4, 'perimeter': 20}

#Getting only the values, keys or both (can be used in loops)
dict1.values() #dict_values(['red', 'square', 25, 4, 20])
dict1.keys() #dict_keys(['color', 'shape', 'area', 'edges', 'perimeter'])
dict1.items() 
#dict_items([('color', 'red'), ('shape', 'square'), ('area', 25), ('edges', 4), ('perimeter', 20)])
Posted by: Guest on May-20-2020
2

get dictionary value in python

my_dict = {'a': 1, 'b': 2, 'c': 3}
# keys = list(item.keys())
# the upper commented code give the list of the keys.
keys = ['a', 'b', 'c', 'd'] # if some body give the list of the keys that wasn't match with my_dict

for key in keys:
    print(my_dict.get(key, 'default value when key not exist'))

"""output:
1
2
3
default value when key not exist
"""
Posted by: Guest on August-05-2021
0

get a value from a dictionary python

#!/usr/bin/python

dict = {'Name': 'Zabra', 'Age': 7}
print "Value : %s" %  dict.get('Age')
print "Value : %s" %  dict.get('Education', "Never")
Posted by: Guest on November-30-2020
1

dictionary in python

#A dictionary has key-value pairs. Here 1,2,3 are the keys and Item1,Item2,Item3 
#are their values respectively. 
dictionaryName = { 1: "Item1", 2: "Item2", 3: "Item3"}

#retrieving value of a particular key
dictionaryName[1]

#retrieving all the keys in a dictionary
dictionaryName.keys()

#retrieving all the values in a dictionary
dictionaryName.values()
Posted by: Guest on November-01-2020
-1

how to get value from key dict in python

# Get a value from a dictionary in python from a key

# Create dictionary
dictionary = {1:"Bob", 2:"Alice", 3:"Jack"}

# Retrieve value from key 2
entry = dictionary[2]

# >>> entry
# Alice
Posted by: Guest on August-15-2020

Code answers related to "how to get a value from a dictionary python"

Python Answers by Framework

Browse Popular Code Answers by Language