Python Dictionaries


Dictionary

Data values are stored in key : value pairs using dictionaries.

A dictionary is an ordered collection that can be changed and it will not support duplicate key-values.

Dictionaries are ordered with Python version 3.7. Dictionaries are not ordered in Python 3.6 and earlier.

Curly brackets {} are used to create dictionaries.

Example :- A simple dictionary

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}

print(mydict)

Output :-

{'id': '101', 'name': 'Suresh', 'salary': 2500}

You can also search for these topics, python dictionaries are also called as, methods of python dictionaries, python dictionaries are mutable, ordered and append the dictionaries using python, python dictionaries best practice, how to count the dictionaries in python, how to contains and copy with python dictionaries, get the key dictionaries using python, python how dictionaries work, how dictionary works internally in python, python dictionary methods.

Dictionary Items

Dictionary items are ordered, modifiable and don't allow duplicates.

In key : value pairs the dictionary items will be presented and can be referred to by the key name.

Example :- Print the dictionary's 'salary' value :

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}
print(mydict["salary"])

Output :-

2500

You can also search for these topics, python dictionary items values, order the python Dictionary Items, python items to list with dictionaries, python method for dictionary items, how to sorted the python dictionary items, python key values for dictionary items, count the dictionary items which is used in python, delete the dictionary items in python, how to equal the values with python, example for python dictionary items, define the function of dictionary items.

Ordered or Unordered?

Dictionaries are ordered as of Python version 3.7. Dictionaries are unordered in Python 3.6 and earlier.

If we say the ordering of dictionaries, it means that there is a definition of the commands, and that order won't change.

Unordered means that you cannot refer to an item by using an index without a defined order.

You can also search for these topics, python set ordered or unordered, python body ordered or unoredered in python, define the python collection ordered or unordered, how to compare the python unordered or ordered, list the combinations of python ordered or ordered, example for ordered and unordered using python, python unordered or ordered key.

Changable

The dictionaries can be modified so that after the dictionary is created we may change, add or remove items.

You can alsp search for these topics, python dictionaries changeable values, python methods are changeable, definition for python changeable, example for python changeable, format and formula for changeable in python, python fields and key changeable using python.

Duplicates Not Allowed

Dictionaries cannot have the same key for two items. If same key found, existing values overwrite the duplicate values

Example :- A simple dictionary with duplicate key "salary" :

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500,
  "salary": 3500
}
print(mydict)

Output :-

{'id': '101', 'name': 'Suresh', 'salary': 3500}

You can also search for these topics, python dictionaries duplicates not allowed access, condition for python duplicates not allowed, fix the date for python duplicates, define the numbers for duplicates using python, python range duplicates.

Dictionary Length

Use the len() function to find out the number of items in a dictionary.

Example :- Print the dictionary's number of items :

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}
print(len(mydict))

Output :-

3

You can also search for these topics, python dictionary length limit, python dictionary word length, check the python length of dictionary, example for dictionary length in python, how to extend the python dictionary length, check the exists of python dictionary length, get dictionary length in python, has the key check length using python dictionary, how to get value of python length of dictionary, how to delete a key of dictionary length.

Check if Key Exists

For example, you may use the in keyword to find out whether a given key is in a dictionary :

Example :- Look in the dictionary to see if "id" is present :

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}

if "id" in mydict:
  print("Yes, 'id' is one of the keys in the mydict dictionary")

Output :-

Yes, 'id' is one of the keys in the mydict dictionary

You can also search for these topics, python dict check if key exists case sensitive, check if key value exists in dict python, python dict check if key already exists, how to check if key exists python dict, Example for python Check if Key Exists.

Dictionary Items - Data Types

Dictionary items can have values of all types of data :

Example :- List of dictionaries with strings, int, booleans, and lists datatypes :

mydict = {
  "id": 101,
  "name": "xy",
  "salary": 2500.56,
  "married": True,
  "dept": ["sales", "service", "accounts"]
}

print(mydict)

Output :-

{'id': 101, 'name': 'xy', 'salary': 2500.56, 'married': True, 'dept': ['sales', 'service', 'accounts']}

You can also search for these topics, python dictionary item data types between, how to change the dictionary items datatypes using python, check the items in dictionary datatypes using python, have different items in datatypes with python, how to use python function items of dictionary with datatypes, find the key value of python dictionary items, check the working of python dictionary items datatypes, python dictionary items datatypes in operator method, Example for python dictionary items with datatypes.

type()

Dictionaries are defined from a Python perspective like objects with the 'dict' data type:

Example :- Print the data type of a dictionary :

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}
print(type(mydict))

Output :-

<class 'dict'>

You can also search for these topics, python dictionary type hint, declaration of python type() dictionaries method, how to check the type() method with python dictionaries, verify the key value using python dictionaries, check the none and null value using python dictionaries, python type() new key value with dictionaries, python nested type() in dictionaries, Example for python type() method in dictionaries.

Python - Access Dictionary Items

There are two to access a dictionary items in python, which is

  1. [] :- Get a dictionary content by refferring to the key name in the square brackets.
  2. get() :- This method is used to get content of a dictionary by providing key name in the method argument.

Accessing Items

Using square brackets, you can retrieve a dictionary's contents by referring to the key name within the brackets and also you can use a method named get(), which returns the same result.

Example 1 :- Retrieve the value of the "id" key :

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}

x = mydict["id"]
y = mydict.get("id")

print(x)
print(y)

Output :-

101
101

You can also search for these topics, python access dictionary keys as attributes, how to access item in ordered dictionary python, access dict items python, get first dictionary items python, Example for Accessing Items in python.

Get Keys and Values

The keys() method is used to return all key names from a dictionary.

The values() method is used to return all key values from a dictionary.

Example :- Get all keys and values from a dictionary:

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}

x = mydict.keys()
y = mydict.values();

print(x)
print(y)

Output :-

dict_keys(['id', 'name', 'salary'])
dict_values(['101', 'Suresh', 2500])

You can also search for these topics, python get keys where value equal, default dict python get keys, how to get number of keys in dictionary python, example for python Get Keys and values, python get values value by key, counter python get value, python get value with default, python how to get value from dictionary, python get highest value in dictionary.

Get Items

The items() method returns each item in a dictionary as a list of tuples.

Example 1 :- Get a list of the key:value pairs :

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}

x = mydict.items()

print(x)

Output :-

dict_items([('id', '101'), ('name', 'Suresh'), ('salary', 2500)])

You can also search for these topics, python dict get item with max value, python get dict item if exists, get one item from dict python, dictionary get item by index python, Example for python Get Items.


Python - Change Dictionary Items

Python provide facilities to change a item value in a dictionary.

You can also search for these topics, python change dict key and value, change dictionary entry python, change dictionary item python create, change dict item python without overwrite.

Change Values

A specific item's value can be changed by referring to its key name :

Example :- Change the "name" to "Babu" :

mydict =	{
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}

mydict["name"] = "Babu"

print(mydict)

Output :-

{'id': '101', 'name': 'Babu', 'salary': 2500}

You can also search for these topics, python change dictionary value in function, how to change dict key value in python, dict change value by key, Example for python Change Values.

Update Dictionary

The dictionary will be updated with the elements from the supplied input using the update() method.

A dictionary or an iterable object containing key:value pairs must be used as an argument to the function.

Example :- The update() method can be used to update the "salary" of the employee :

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}
mydict.update({"salary": 5000})

print(mydict)

Output :-

{'id': '101', 'name': 'Suresh', 'salary': 5000}

You can also search for these topics, python update dictionary while iterating, what is dictionary update in python, how to update empty dictionary in python, python recursive update dictionary, Example for python Update Dictionary.

Python - Add Dictionary Items

Adding Items

Each entry in the dictionary is added using an index key that has a value assigned to the new item.

Example :- Adding a new key "dept" :

mydict =	{
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}
mydict["dept"] = "sales"
print(mydict)

Output :-

{'id': '101', 'name': 'Suresh', 'salary': 2500, 'dept': 'sales'}

You can also search for these topics, python add dictionary item at beginning, how to add dictionary in python, python empty dictionary add item, python dictionary add item with same key, Example for python Adding Items.

Update Dictionary

The update() method updates the dictionary with items from a provided input. If the item does not already exist, it will be added to the system.

A dictionary or an iterable object with key:value pairs must be used as the argument to the function

Example :- The update() method can be used to add a dept item to the dictionary :

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}
mydict.update({"dept": "sales"})

print(mydict)

Output :-

{'id': '101', 'name': 'Suresh', 'salary': 2500, 'dept': 'sales'}

You can also search for these topics, python update dictionary while iterating, what is dictionary update in python, how to update empty dictionary in python, python recursive update dictionary, Example for python Update Dictionary.

Python - Remove Dictionary Items

Remove things from a dictionary can be done in a variety of ways :

The pop() method and del keyword are used to delete an item from a dictionary.

Example 1 :- Removes an item using pop() method and del keyword :

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}

mydict.pop("name")
print(mydict)

del mydict["salary"]
print(mydict)

Output :-

{'id': '101', 'salary': 2500}
{'id': '101'}

The clear() method is used to delete all items from a dictionary and make it empty dictionary.

Example 2 :- Using the clear() method, the dictionary is emptied of all items :

mydict =	{
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}
mydict.clear()
print(mydict)

Output :-

{}

The del keyword is used to delete all items in a dictionary and also delete the dictionary itself.

Example 3 :- The del keyword can also be used to remove the entire dictionary :

mydict =	{
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}
del mydict
print(mydict) #this will cause an error because "mydict" no longer exists.

Output :-

Traceback (most recent call last):
File "demo_dictionary_del3.py", line 7, in < module>
print(mydict) #this will cause an error because "mydict" no longer exists.
NameError: name 'mydict' is not defined

You can also search for these topics, delete dictionary element python, python remove dictionary entry while iterating, python dict how to remove item, dict remove item python condition, Example for python Removing Items.

Python - Loop Dictionaries

Using a for loop, you may loop through a dictionary.

In a dictionary looping through, the return value is the dictionary keys, but there are several methods to return the dictionary's actual values.

Example 1 :- Print out the dictionary's key names one by one :

mydict =	{
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}
for x in mydict:
  print(x)

Output :-

id
name
salary

Example 2 :- Print all dictionary values one by one :

mydict =	{
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}
for x in mydict:
  print(mydict[x])

Output :-

101
Suresh
2500

Example 3 :- Use the items() method to loop through both keys and values :

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}
for x, y in mydict.items():
  print(x, " = ", y)

Output :-

id = 101
name = Suresh
salary = 2500

You can also search for these topics, iterate through dictionary python with index, how to loop through dictionary in python, python loop through dictionary in order, python iterate through dictionary sorted by value, Example for python Loop Through a Dictionary.

Python - Copy Dictionaries

By entering dict2 = dict1, you will just be copying the dictionary's contents, and any modifications made to dict1 will immediately be made to dict2.

Making a copy can be done in several ways, including by using the built-in dictionary method copy() and dict().

Example :- make a copy of a dictionary's contents using copy() and dict() methods :

mydict = {
  "id": "101",
  "name": "Suresh",
  "salary": 2500
}

mydict2 = mydict.copy()
mydict3 = dict(mydict)

print(mydict2)
print(mydict3)

Output :-

{'id': '101', 'name': 'Suresh', 'salary': 2500}
{'id': '101', 'name': 'Suresh', 'salary': 2500}

You can also search for these topics, how to copy data from one dictionary to another in python, python copy dictionary except one key, copy part of dictionary python, make copy dictionary python, Example for python Copy a Dictionary.

Nested Dictionaries

When a dictionary contains another dictionary, this is called nesting dictionary.

Exmaple 1 :- A dictionary that contains three dictionaries should be constructed :

employees = {
  "emp1" : {
    "name" : "aa",
    "year" : 2004
  },
  "emp2" : {
    "name" : "bb",
    "year" : 2007
  },
  "emp3" : {
    "name" : "cc",
    "year" : 2011
  }
}

print(employees)

Output :-

{'emp1': {'name': 'aa', 'year': 2004}, 'emp2': {'name': 'bb', 'year': 2007}, 'emp3': {'name': 'cc', 'year': 2011}}

If you wish to combine three dictionaries into one, For example.

Example 2 :- Construct two dictionaries, then create a dictionary that contains the other two dictionaries :

emp1 = {
  "name" : "aa",
  "year" : 2004
}
emp2 = {
  "name" : "bb",
  "year" : 2007
}

employees = {
  "emp1" : emp1,
  "emp2" : emp2
}

print(employees)

Output :-

{'emp1': {'name': 'aa', 'year': 2004}, 'emp2': {'name': 'bb', 'year': 2007}}

You can also search for these topics, how to get value from nested dictionary in python, python nested dictionary example, what is nested dictionary in python, how to update nested dictionary in python, Example for python Nested Dictionaries.