<dictionary-object> = {<key>:<value>,<key:value>,.....}
According to the syntax
Points to remember
While creating a dictionary always remember these points:
Observe the below given examples:
d = {'Mines':'Rajesh Thakare','HR':'Dinesh Lohana','TPP':'Kamlesh Verma','School':'A. Vijayan','Hospital':'Shailendra Yadav'}
d = {1:'Sharda',2:'Champa',3:'Babita',4:'Pushpa',5:'Chandirka',6:'Meena'}
d = {1:100,2:200,3:300,4:400}
Now understand the key-value pairs:
d = {1:'Virat Kohli',2:'Ajinkya Rehane',3:'Subhman Gill'}
#Priting with keys
print(d[1],d[3])
#Printing all values
print(d)
The process of taking a key and finding a value from the dictionary is known as lookup. Moreover, you cannot a access any element without key. If you try to access a value with key doesn’t exist in the dictionary, will raise an error.
Now have a look at the following code:
d = {'Mines':'Rajesh Thakare','HR':'Dinesh Lohana','TPP':'Kamlesh Verma','School':'A. Vijayan','Hospital':'Shailendra Yadav'}
for i in d:
print(i, ":",d[i])
In the above code you can see the variable i prints the key and d[i] prints the associated value to the key.
d = {'Mines':'Rajesh Thakare','HR':'Dinesh Lohana','TPP':'Kamlesh Verma','School':'A. Vijayan','Hospital':'Shailendra Yadav'}
for i,j in d.items():
print(i, ":",j)
Here, I have separated the values using two variables in the loop.
You can also access the keys and values using d.keys() and d. values() respectively. It will return the keys, and values in the form of sequence. Observe this code and check the output yourself:
d = {'Mines':'Rajesh Thakare','HR':'Dinesh Lohana','TPP':'Kamlesh Verma','School':'A. Vijayan','Hospital':'Shailendra Yadav'}
print(d.keys())
print(d.values())
pr = dict(name='Ujjwal',age=32,salary=25000,city='Ahmedabad')
print(pr)
You can also specify the key:pair value in following manners:
pr = dict({'name':'Ujjwal','age':32,'salary':25000,'city':'Ahmedabad'})
print(pr)
You can also specify the key-values in the form sequences (nested list) as well. Observe the following code:
pr = dict([['name','Ujjwal'],['age',32],['salary',25000],['city','Ahmedabad']])
print(pr)
pr = dict([['name','Ujjwal'],['age',32],['salary',25000],['city','Ahmedabad']])
pr['dept']='school'
print(pr)
d = dict({'name':'Ujjwal','age':32,'salary':25000,'city':'Ahmedabad'})
d['salary']=30000
print(d)
d = dict({'name':'Shyam','age':32,'salary':25000,'city':'Ahmedabad'})
del d['age']
d = dict({'name':'Shyam','age':32,'salary':25000,'city':'Ahmedabad'})
if 'name' in d:
print("Key found")
else:
print("Key not found")
if 'Shyam' in d.values():
print("Value found")
else:
print("Value not found")
Consider this example:
import json
d={'Virat':45,'Rehane':56,'Pujara':76,'Rahul':34}
print(json.dumps(d,indent=3))
Install json using pip insall json command.
Observe the output yourself.
Observe the following code:
import json
c=0
txt="This is a text This text is accepted by user input \
User input is given thorugh input() function."
w=txt.split()
d={}
for i in w:
key = i
if key not in d:
c=w.count(key)
d[key]=c
print("Frequency",w)
print(json.dumps(d,indent=1))
d={'Virat':45,'Rehane':56,'Pujara':76,'Rahul':34}
len(d)
The above code will return 4 as there are 4 key:value pairs available in the code.
d={'Virat':45,'Rehane':56,'Pujara':76,'Rahul':34}
print(d.get('Virat'))
print(d.get('Sachin','Not Found'))
Here, d.get(‘Virat’) returns the value 45 whereas d.get(‘Sachin’,’Not Found’) will return “Not Found” error message.
d={'Virat':45,'Rehane':56,'Pujara':76,'Rahul':34}
l=d.items()
for i in d:
print(i)
The above code will return this output:
('Virat', 45)
('Rehane', 56)
('Pujara', 76)
('Rahul', 34)
d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}
print(d.keys())
The above code will return dict_keys([‘Ramesh’, ‘Suresh’, ‘Akhilesh’, ‘Sameer’]) as output.
d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}
print(d.values())
The above code will return idct_values([1500,20000,21000,22000]) as output.
n=int(input("How many customers?"))
l=[]
for i in range(n):
v=input("Enter names:")
l.append(v)
d=dict.fromkeys(l,2500)
print(d)
Here dict.fromkeys() method create a dictionary with different keys of names provided into list l with the similar value 2500. Observe this output:
The fromkeys() method requires an iterable sequence as the first parameter. You cannot pass an integer or a single character. When you do not pass any value as a parameter then it will assign None in front of the key.
d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}
d.setdefault('Sagar',34000)
If you provide only one parameter, it is considered as key and value will be added None.
d1={'One':10,'Two':20}
d2={'One':30,'Four':40}
d1.update(d2)
print(d1)
It will return {‘One’: 30, ‘Two’: 20, ‘Four’: 40} as output.
d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}
d1=d.copy()
It will copy the dictionary one to another. You can use the assignment operator to copy the dictionaries.
d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}
d1=d
d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}
d.pop(2)
The above code will return “Vatsal” as it gets deleted from the dictionary.
d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}
d.pop(5,"Key Not Present")
Here it will give the message Key Not Present. You can delete an element using del keyword as well.
d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}
del d[2]
print(d)
d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}
d.popitem()
Here it will return (4,’Mohan’) as output.
d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}
d.clear()
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}
print(sorted(d))
The above code will return the list of keys as : [2, 4, 11, 30]
If you want to sort keys in descending order use reverse=True. Obseve this:
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}
print(sorted(d, reverse=True))
The above code output is: [30, 11, 4, 2]
If you want to sort the values it will be used in this manner.
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}
print(sorted(d.values(), reverse=True))
Observe the result yourself and understand it.
Similarly, you can use the items() method to sort key-value pairs and the answer will be returned in the form of tuples with key-value pairs sorted by keys.
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}
print(max(d))
print(max(d.values()))
The second line returns 30 and the third line returns ‘Vatsal’.
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}
print(min(d))
print(min(d.values()))
It will make the sum of all the specified keys or values. Example:
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}
print(sum(d))
20 videos|20 docs|5 tests
|
|
Explore Courses for Humanities/Arts exam
|