how to access value in dictionary python code example

Example 1: 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)])

Example 2: dictionary in python

# Dictionaries in Python are used to store set of data like Key: Value pair

# the syntax of a dictionary in Python is very simple we use {} inside that
	# we define {Key: Value}, to separate multiple values we use','
programming_dictionary = {
    "Bug": "An error in a program that prevents the program from running as expected.",
  
    "Function": "A piece of code that you can easily call over and over again.",
  
  	"Loop": "The action of doing sommething again and again",
}
# to retrieve the values from a dictionary we use the Key name as an Index
# retrieving the Function's definition
print(programming_dictionary["Function"])	# this will print the definition of Function

# if you wanna print all the entries in the dictionary you can do that by for loop
for key in programming_dictionary:
  print(programming_dictionary[key])	# prints all entries
  
# adding items to a dictionary
# the following code will add another entry to the dictionary called Variable
programming_dictionary["Variable"] = "The label to store some sort of data"
print(programming_dictionary["Variable"])

# editing the values of a key 
# editing the value of variable
programming_dictionary["Variable"] = "Variables are nothing but reserved memory locations to store values. This means that when you create a variableyou reserve some space in memory"

# if you learnt something from this please upvote it

Example 3: 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")

Example 4: how to create dictionary in python

d = {'key': 'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'key': 'value', 'mynewkey': 'mynewvalue'}

Example 5: python dictionary access value by key

# 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')

Example 6: python dict access

my_dict = {'name':'Jack', 'age': 26}
my_dict['name']