Python Dictionaries
Published: 2023-05-11 07:01:47

## 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 –

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

```

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

```python
#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)

```

**Output**  –

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

```

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

Let’s see how we can do that –

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

```

**Output**  –

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

```

## 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 –

```python
#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)

```

**Output –**

```python
{}
{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'}}}

```

## 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 –

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

```

**Output –**

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

```

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()](https://www.scaler.com/topics/clear-in-python/)

Consider the following code –

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

```

**Output**  –

```python
{}

```

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


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

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

```

**Output**  –

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

```

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

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


```

**Output**  –

```python
James
Apple
Jake
Banana,Cherry,Kiwi

```

### Properties of Python Dictionary Keys

I am sure by now you have realised that  [Python dictionary values](https://www.scaler.com/topics/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 –

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

```

**Output**  –

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

```

2.  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](https://www.scaler.com/topics/python-dictionary-keys/).

### 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.