DEV Community

atchukolanaresh
atchukolanaresh

Posted on

Python Dictionaries

Creating a Dictionary in Python

Creating a Python dictionary is as simple as placing the required key and value pairs within a curly bracket.

“{}”.

A colon separates the key-value pair.

“:”

When there are multiple key-value pairs, they are separated by a comma.

“,”

The syntax of declaring a dictionary in python is as follows –

my_dict={'Name':'Ravi',"Age":'32'}

Enter fullscreen mode Exit fullscreen mode

Now let’s look at some different ways of creating a Python dictionary –

#creating an empty dictionary
my_dict={}
#creating a dictionary with integer keys
fruits={'1':'apple','2':'banana','3':'cherry'}
#creating a dictionary with mixed keys
random_dict={'1':'red','Name':'Anushka'}
print(my_dict)
print(fruits)
print(random_dict)

Enter fullscreen mode Exit fullscreen mode

Output

{}
{'1': 'apple', '2': 'banana', '3': 'cherry'}
{'1': 'red', 'Name': 'Anushka'}

Enter fullscreen mode Exit fullscreen mode

Another way we can create a dictionary in Python is using the built-in dict() function!

Let’s see how we can do that –

Dict = dict([(1, 'Scaler'), (2, 'Academy')])   
print("\nCreate a Dictionary by using  dict(): ")   
print(Dict)

Enter fullscreen mode Exit fullscreen mode

Output

Create a Dictionary by using  dict(): 
{1: 'Scaler', 2: 'Academy'}

Enter fullscreen mode Exit fullscreen mode

Updating Dictionary in Python

We can do multiple things when trying to update a dictionary in Python. Some of them are –

  1. Add a new entry.
  2. Modify an existing entry.
  3. Adding multiple values to a single key.
  4. Adding a nested key.

Now let’s try to implement these through code –

#creating an empty dictionary
my_dict={}
print(my_dict)
#adding elements to the dictionary one at a time
my_dict[1]="James"
my_dict[2]="Jim"
my_dict[3]="Jake"
print(my_dict)
#modifying existing entry
my_dict[2]="Apple"
print(my_dict)
#adding multiple values to a single key
my_dict[4]="Banana,Cherry,Kiwi"
print(my_dict)
#adding nested key values
my_dict[5]={'Nested' :{'1' : 'Scaler', '2' : 'Academy'}}
print(my_dict)

Enter fullscreen mode Exit fullscreen mode

Output –

{}
{1: 'James', 2: 'Jim', 3: 'Jake'}
{1: 'James', 2: 'Apple', 3: 'Jake'}
{1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana,Cherry,Kiwi'}
{1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana,Cherry,Kiwi', 5: {'Nested': {'1': 'Scaler', '2': 'Academy'}}}

Enter fullscreen mode Exit fullscreen mode

Deleting Dictionary Elements

Now that we have covered how to update Python dictionaries, let’s look at how we can either delete the dictionary entirely or remove individual entries.

To remove an entire dictionary in Python, we use the “del” keyword.

Let’s check out its implementation –

my_dict={1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana,Cherry,Kiwi'}
del my_dict[4]
print(my_dict)

Enter fullscreen mode Exit fullscreen mode

Output –

{1: 'James', 2: 'Apple', 3: 'Jake'}

Enter fullscreen mode Exit fullscreen mode

Using

del

We deleted the entries for a specific key in the above example.

Now, if we want to clear an entire dictionary in Python, we will use the

.clear()

Consider the following code –

my_dict={1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana,Cherry,Kiwi'}
my_dict.clear()
print(my_dict)

Enter fullscreen mode Exit fullscreen mode

Output

{}

Enter fullscreen mode Exit fullscreen mode

As you can see, the entire content of the dictionary “my_dict” was removed.

Use the for loop along with the items() method:

my_dict={1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana,Cherry,Kiwi'}
for x in my_dict.items(): 
    print(x)

Enter fullscreen mode Exit fullscreen mode

Output

(1, 'James')
(2, 'Apple')
(3, Jake')
(4, 'Banana, Cherry, Kiwi')

Enter fullscreen mode Exit fullscreen mode

4. Use the for loop along with the values() method:

my_dict={1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana,Cherry,Kiwi'}
for x in my_dict.values(): 
    print(x)


Enter fullscreen mode Exit fullscreen mode

Output

James
Apple
Jake
Banana,Cherry,Kiwi

Enter fullscreen mode Exit fullscreen mode

Properties of Python Dictionary Keys

I am sure by now you have realised that Python dictionary values have no restrictions and can be any Python object. The same is not true for keys.

So there are specific properties of keys we must be aware of to work with Python dictionaries efficiently –

  1. Duplicate keys are not allowed. When duplicate keys are encountered in Python, the last assignment is the one that wins.

For example –

my_dict={1: 'James', 2: 'Apple', 3: 'Jake', 1: 'Banana,Cherry,Kiwi'}
print(my_dict)

Enter fullscreen mode Exit fullscreen mode

Output

{1: 'Banana, Cherry, Kiwi', 2: 'Apple', 3: 'Jake'}

Enter fullscreen mode Exit fullscreen mode
  1. Keys are immutable- they can only be numbers, strings or tuples.

We have seen several examples earlier in this article to see how this works.

Click here to learn more about Python Dictionary Keys() Method.

Built-in Python Dictionary Functions & Methods

Now that we know how to work with Python dictionaries let’s look at some dictionary functions and dictionary methods.

Dictionary Functions

cmp(dict1,dict2):

It compares the items of both the dictionaries and returns true if the value of the first dictionary is greater than the second else returns false.

len(dict):

It gives the total number of items in the dictionary.

str(dict):

It produces a printable string representation of the dictionary.

all(dict):

It returns true if all the keys in the dictionary are true.

any(dict):

It returns true if any key in the dictionary is true.

sorted(dict):

It returns a new sorted list of keys in a dictionary.

Python Dictionary Methods

dict.clear()

It removes all elements of the dictionaries.

dict.copy()

It returns a copy of the dictionary.

dict.pop()

It removes an element from the specified key.

dict.get()

It is used to get the value of the specified key.

dict.fromkeys()

It creates a new dictionary with keys from seq and values set to value.

dict.items()

It returns the list of dictionary tuple pairs.

dict.keys()

It returns the list of keys of the dictionary.

dict.update(dict2)

It adds the dict2’s key-value pairs to dict.

dct.has_key()

It returns true if the specified key is present in the dictionary else false.

Top comments (1)

Collapse
 
vineetjadav73 profile image
vineetjadav

Finding a reputable data science course in Delhi can be daunting, but this one is worth every penny. Comprehensive syllabus and experienced instructors – couldn't ask for more!