Dictionary in Python with Syntax & Example

Created with Sketch.

A dictionary in Python is a mutable, unordered collection of key-value pairs, where each key must be unique. Dictionaries are useful for storing and retrieving data efficiently based on a specific key. Here is the syntax and an example of using dictionaries in Python:

Syntax:

# Creating an empty dictionary
my_dict = {}

# Creating a dictionary with initial values
my_dict = {key1: value1, key2: value2, key3: value3}

# Accessing a value using a key
value = my_dict[key]

# Modifying a value
my_dict[key] = new_value

# Adding a new key-value pair
my_dict[new_key] = new_value

# Deleting a key-value pair
del my_dict[key]

# Checking if a key exists in the dictionary
if key in my_dict:
    # Do something

# Getting the list of keys
keys = my_dict.keys()

# Getting the list of values
values = my_dict.values()

# Getting the list of key-value pairs as tuples
items = my_dict.items()

Example:

 
# Creating a dictionary with student information
student_info = {
    'name': 'John Doe',
    'age': 20,
    'grade': 'A',
    'courses': ['Math', 'English', 'Science']
}

# Accessing values
name = student_info['name']
age = student_info['age']
courses = student_info['courses']

# Modifying values
student_info['age'] = 21

# Adding a new key-value pair
student_info['gender'] = 'Male'

# Deleting a key-value pair
del student_info['grade']

# Checking if a key exists
if 'grade' in student_info:
    print("Grade information exists.")
else:
    print("Grade information does not exist.")

# Displaying keys, values, and items
print("Keys:", student_info.keys())
print("Values:", student_info.values())
print("Items:", student_info.items())

Dictionaries provide a flexible and efficient way to organize and retrieve data based on keys. They are commonly used in various Python applications.

Here is the list of all Dictionary Methods

MethodDescriptionSyntax
copy()Copy the entire dictionary to new dictionarydict.copy()
update()Update a dictionary by adding a new entry or a key-value pair to anexisting entry or by deleting an existing entry.Dict.update([other])
items()Returns a list of tuple pairs (Keys, Value) in the dictionary.dictionary.items()
sort()You can sort the elementsdictionary.sort()
len()Gives the number of pairs in the dictionary.len(dict)
cmp()Compare the values and keys of two dictionariescmp(dict1, dict2)
Str()Make a dictionary into a printable string formatStr(dict)

clear():

  • Removes all items from the dictionary.
 
my_dict = {'name': 'John', 'age': 25}
my_dict.clear()

copy():

  • Returns a shallow copy of the dictionary.
original_dict = {'name': 'John', 'age': 25}
copied_dict = original_dict.copy()

fromkeys():

  • Creates a new dictionary with specified keys and values.
keys = ['name', 'age', 'city']
default_value = 'unknown'
new_dict = dict.fromkeys(keys, default_value)

get():

  • Returns the value for the specified key. If the key is not found, it returns a default value (or None).
my_dict = {'name': 'John', 'age': 25}
value = my_dict.get('name', 'Default')

items():

  • Returns a view of key-value pairs as tuples.
my_dict = {'name': 'John', 'age': 25}
items = my_dict.items()

keys():

  • Returns a view of all keys in the dictionary.
my_dict = {'name': 'John', 'age': 25}
keys = my_dict.keys()

values():

  • Returns a view of all values in the dictionary.
my_dict = {'name': 'John', 'age': 25}
values = my_dict.values()

pop():

  • Removes and returns the value for a specified key.
my_dict = {'name': 'John', 'age': 25}
value = my_dict.pop('name')

popitem():

  • Removes and returns the last key-value pair as a tuple.
my_dict = {'name': 'John', 'age': 25}
key, value = my_dict.popitem()

setdefault():

  • Returns the value for a specified key. If the key is not found, it inserts the key with a specified default value.
my_dict = {'name': 'John', 'age': 25}
value = my_dict.setdefault('gender', 'Male')

update():

  • Updates the dictionary with key-value pairs from another dictionary or iterable.
my_dict = {'name': 'John', 'age': 25}
new_data = {'age': 26, 'city': 'New York'}
my_dict.update(new_data)

pop():

  • Removes and returns the value for a specified key.
my_dict = {'name': 'John', 'age': 25}
value = my_dict.pop('name')

popitem():

  • Removes and returns the last key-value pair as a tuple.
my_dict = {'name': 'John', 'age': 25}
key, value = my_dict.popitem()

These are just a few of the many dictionary methods available in Python. The official Python documentation is a valuable resource for a comprehensive list of methods and their descriptions: Python Dictionary Methods.

Leave a Reply

Your email address will not be published. Required fields are marked *