Site icon Care All Solutions

Creating and Accessing Dictionaries

Creating Dictionaries

A Python dictionary is created by enclosing a comma-separated list of key-value pairs within curly braces {}. Each key-value pair is separated by a colon :.

Python

# Empty dictionary
empty_dict = {}

# Dictionary with elements
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}

Accessing Dictionary Elements

Python

person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(person['name'])  # Output: Alice

Python

person = {'name': 'Alice', 'age': 30}
print(person.get('address', 'Unknown'))  # Output: Unknown

Important points:

How do you create an empty dictionary?

Use {} to create an empty dictionary.

Can a dictionary contain duplicate keys?

No, dictionary keys must be unique.

Can I create a dictionary from a list of tuples?

Yes, using the dict() constructor.

How do you access a value in a dictionary?

Use square brackets [] with the key.

What happens if you try to access a non-existent key?

It raises a KeyError.

Are dictionaries ordered in Python?

In Python 3.7 and later, dictionaries maintain insertion order.

Can I use a list as a key in a dictionary?

No, because lists are mutable.

How do you remove a key-value pair from a dictionary?

Use the del keyword or the pop() method.

What is a dictionary comprehension?

A concise way to create dictionaries using a similar syntax to list comprehensions.

How do you create a dictionary comprehension?

Use curly braces {} and specify key-value pairs within the expression.

Read More..

Exit mobile version