Python dictionary operations

What is a Python dictionary?

Example,
student = {"Name": "Peter", "Age": "20"}
student = dict(Name="Peter", Age: "20")

How can we access an element from the python dictionary?

student = {"Name": "Peter", "Age": "20"}
print (student['Age'])
print (student['DOB'])
print (student.get('Name'))
print (student.get('DOB', '1/1/2001'))Output,
> 20
> KeyError: 'DOB'
> Peter
> 1/1/2001

How to update the python dictionary?

student = {"Name": "Peter", "Age": "20"}
student.update(Name="James")
print (student)
student.update(DOB="1/01/2001")
print (student)Output,> {"Name": "James", "Age": "20"}
> {"Name": "James", "Age": "20", "DOB": "1/01/2001"}

How to delete the item from python dictionary?

student = {"Name": "Peter", "Age": "20"}
removed_item = student.pop('Age')
print (student)
print (removed_item)Output,> {"Name": "Peter"}
> 20

How to iterate through the python dictionary?

student = {"Name": "James", "Age": "20", "DOB": "1/01/2001"}
for i in student:
    print(student[i])Output,
> James
> 20
> 1/01/2001

Python Dictionary comprehension

dict1= {i:i*2 for i in range(1,5)}
print (dict1)Output,
{1:1, 2:4, 3:6, 4:8}

No comments:

Powered by Blogger.