Understand Dictionary{} with Python Example

https://miro.medium.com/max/1200/0*tqE1hmGCL5QRaryI

Original Source Here

Understand Dictionary{} with Python Example

Handy concept of data structure in python

Photo by Alvaro Reyes on Unsplash

A dictionary is an unordered collection of items separated by commas inside curly braces ‘{}’. Items in a dictionary are always in the form of key-value pairs. The value present in the dictionary is displayed using their respective keys. A value in a dictionary can be duplicated and can be of any datatype. But, a key can never recur. (it must have unique values).

Creating a dictionary

  1. Creating empty dictionary
Dictionary = {}print(Dictionary)Output:
{}

2. Creating dictionary using integer keys

D = {1: ‘lion’, 2: ‘tiger’, 3: ‘zebra’}print(D)Output:
{1: ‘lion’, 2: ‘tiger’, 3: ‘zebra’}

3. Creating dictionary using mixed keys

D = {‘animal’: ‘tiger’, 4: [1, 2, 3]}print(D)Output:
{‘animal’: ‘tiger’, 4: [1, 2, 3]}

4. Creating dictionary using Dict() function

D = dict({1: ‘lion’, 2: ‘tiger’, 3: ‘zebra’})print(D)Output:
{1: ‘lion’, 2: ‘tiger’, 3: ‘zebra’}

Accessing a dictionary

  1. Accessing dictionary using []
d = {‘animal’: ‘tiger’, ‘ani’: ‘zebra’}print(d[‘animal’])Output:
tiger

Explanation:

Here, the ‘[]’ is to define the key to be accessed. In the above program, we have defined ‘animal’ to access from the dictionary. The value of that key is the output (tiger).

2. Accessing dictionary using get()

p = {‘animal’: ‘tiger’, ‘ani’: ‘zebra’}print(p.get(‘ani’))Output:
Zebra

Explanation:

The get() function performs the same function as that of ‘[]’. The only difference is the way of writing it.

Modifying/ Adding dictionary elements

  1. Updating a dictionary
S = {‘color1’: ‘pink’, ‘color2’: ‘red’}S[‘color1’] = ‘green’Output:
{‘color1’: ‘green’, ‘color2’: ‘red’}

Explanation:

Here, the program is to update the color ‘pink’ to ‘green’ in the dictionary. So we have assigned ‘color1’ to green. The output shows the update made.

2. Adding an item to a dictionary:

S = {‘color1’: ‘green’, ‘color2’: ‘red’}S[‘color3’] = ‘yellow’Output:
{‘color1’: ‘green’, ‘color2’: ‘red’, ‘color3’: ‘yellow’}

Explanation:

Here, the program is to add another key-value pair to the dictionary. So we assign a new value ‘yellow’ to a new key, ‘color3’. The output shows the added key-value pair.

Deleting dictionary elements

  1. pop(): The pop() function returns the value specified to remove from the dictionary. The pop function allows only one item to be removed at a time.

Program:

R = {1: ’n’, 2: ‘f’, 3: ‘w’, 4: ‘y’, 5: ‘i’}print(R.pop(3))
print(R)
Output:
w
{1: ’n’, 2: ‘f’, 4: ‘y’, 5: ‘i’}

2. popitem(): The popitem() method returns the last value present in the dictionary.

Program:

R = {1: ’n’, 2: ‘f’, 4: ‘y’, 5: ‘i’}print(R.popitem())
print(R)
Output:
(5, ‘i’)
{1: ’n’, 2: ‘f’, 4: ‘y’}

3. clear(): The clear() function removes all the items from the dictionary, making them empty.

Program:

R = {1: ’n’, 2: ‘f’, 4: ‘y’}print.clear()Output:
{}
9

4. del: ‘del’ deletes the entire dictionary.

Program:

R = {1: ’n’, 2: ‘f’}del Rprint(R)Output:
Traceback (most recent call last):
File “<string>”, line3, in <module>
print(R)
NameError: name ‘R’ is not defined

Dictionary methods

There are several methods in the dictionary where a few of them have already been explored in detail. Below are some of the methods explored:

  1. items(): The items() method, returns a new object of the items present in a dictionary in a key-value format.

Program:

P = {0:’tiger’, 1:’lion’, 2:’zebra’}for i in P.items():
print(i)
Output:
(0, ‘tiger’)
(1, ‘lion’)
(2, ‘zebra’)

2. keys(): The keys() method, returns all the dictionary keys present in the dictionary.

Program:

Y = {‘tiger’: ‘a’, ‘lion’: ‘b’, ‘zebra’: ‘c’}print(Y.keys())Output:
dict_keys([‘tiger’, ‘lion’, ‘zebra’])

Dictionary membership test

A membership test used in a dictionary is similar to the rest of the data structures. It checks whether the defined element is present in the set or not. If the element is present in the set, it returns the output as true, or else it returns the output as false.

Note Membership tests only for keys, not values.

Program:

Test = {1: 34, 2: 23, 3: 56, 4: 99, 5: 55}print(1 in Test)
print(3 not in Test)
print(7 in Test)
Output:
True
False
False

Explanation:

  • In the 1st print statement, the requirement is to check whether the key ‘1’ is present in the dictionary. Since the key is present it returns the output as true.
  • In the 2nd print statement, the requirement is to check whether the key ‘3’ is not present in the dictionary. We can observe that the defined key is present in the dictionary. Hence the output is returned as false.
  • In the 3rd statement, the requirement is to check whether the key ‘7’ is present in the dictionary. Since the key is not present it returns the output as false.

Iteration using dictionary

Program:

R = {1: ’n’, 2: ‘f’, 4: ‘y’, 5: ‘i’}for d in R:
print(R[d])
Output:
n
f
y
i

Explanation:

In the above example, each key-value of the dictionary is printed. i.e., the ‘for’ loop keeps executing the program till there is no element left.

Some built-in functions using dictionary

  1. all(): The all() function returns the output only if all the keys of a dictionary are true. It also returns true if the dictionary is empty.

Program:

P = {1: ’n’, 2: ‘f’, 4: ‘y’, 5: ‘i’}print(all(P))Output:
True

2. any(): The any() function returns the value as true if any key in the dictionary is true. Also, if the dictionary is empty, it returns the value as false.

Program:

P = {}print(any(P))Output:
False

3. sorted(): The sorted() function returns the values of a dictionary in a sorted form.

Program:

P = {1: 34, 2: 23, 3: 56, 4: 99, 5: 55}print(sorted(squares))Output:
[23, 34, 55, 56, 99]

AI/ML

Trending AI/ML Article Identified & Digested via Granola by Ramsey Elbasheer; a Machine-Driven RSS Bot

%d bloggers like this: