DEV Community

Sakshi
Sakshi

Posted on

Dictionary📚 - Python

Python Unleash'd 12

Hi

Starting with new data structure today.
We are done with sets.

Maps in C++ never annoyed me, so helpful data structure, I expect same from dictionary.

What is dictionary in python?

  • Stores values in key value pair.
  • curly brackets are used
  • Keys are immutable, while values are duplicate and mutable
  • Values can be of any data type
  • Key names are case sensitive

Here is an example from GeeksForGeeks too see how to create dictionary

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

Enter fullscreen mode Exit fullscreen mode

Other way to create dictionary is by using

dict function

Image description

Check length of dictionary using len()

`len(Dict)1 returns length of dictionary.

Image description

How to add elements to dictionary

As we do in C++, we can access dictionary values with keys, see

Image description

While adding a value, if the key-value already exists, the value gets updated otherwise a new Key with the value is added to the Dictionary.

See how dictionary gets updated

Image description

There is another way to access items.

dictionary2.get(3)

Accessing nested dictionary items

dictionary2 = {0 : 'zero', 1:{1:"one", 2:"two"}}
print(dictionary2[1][2])

Deletion

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}


print("Dictionary =")
print(Dict)
del(Dict[1])
print("Data after deletion Dictionary=")
print(Dict)

Thanks for reading

Top comments (0)