Example 1: python dictionary to json
import json
appDict = {
'name': 'messenger',
'playstore': True,
'company': 'Facebook',
'price': 100
}
app_json = json.dumps(appDict)
print(app_json)
Example 2: dictionary in python does not support append operation
dict_append = {"1" : "Python", "2" : "Java"}
dict_append.update({"3":"C++"}) # append doesn't supported in dict
# instead , use update in dict
print(dict_append)
# output : {'1': 'Python', '2': 'Java', '3': 'C++'}
Example 3: 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 4: python make a dictionary
#title : Dictionary Example
#author : Joyiscold
#date : 2020-02-01
#====================================================
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
#Assigning a value
thisdict["year"] = 2018
Example 5: how to use dictionaries in python
student_data = {
"name":"inderpaal",
"age":21,
"course":['Bsc', 'Computer Science']
}
#the keys are the left hand side and the values are the right hand side
#to print data you do print(name_of_dictionary['key_name'])
print(student_data['name']) # will print 'inderpaal'
print(student_data['age']) # will print 21
print(student_data['course'])[0]
#this will print 'Bsc' since that field is an array and array[0] is 'Bsc'
Example 6: dict python
a = {'a': 123, 'b': 'test'}