DEV Community


Posted on

Dictionaryđź“š - Python

Python Unleash'd 12


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

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

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.


Accessing nested dictionary items

dictionary2 = {0 : 'zero', 1:{1:"one", 2:"two"}}


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

print("Dictionary =")
print("Data after deletion Dictionary=")

Thanks for reading

Top comments (0)