Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program To Create A Dictionary With A Dictionary Literal
Dictionaries are used to store data values in key:value pairs. Unlike other data types that hold only a single value as an element, dictionaries use key-value pairs to make data access more effective.
Dictionary keys must be unique, so no duplicate keys are allowed. Dictionary items are ordered (as of Python 3.7+), changeable, and mutable. This means we can add or remove items after the dictionary is created.
Creating a Dictionary with Dictionary Literals
We can create a dictionary using curly brackets {}. Place elements inside curly brackets, separate keys and values with colons :, and separate each key-value pair with commas.
Basic Dictionary Creation
Here's how to create different types of dictionaries using dictionary literals ?
# Dictionary with integers and strings
flowers = {1: 'rose', 2: 'lily', 3: 'jasmine'}
# Dictionary with integers only
numbers = {1: 5, 3: 7, 8: 6, 9: 4}
# Dictionary with strings and lists (mixed types)
heroes = {'spider': 'man', 'captain': 'america', 'iron': ['tony', 'starks']}
# Empty dictionary
empty_dict = {}
print("Flowers:", flowers)
print("Numbers:", numbers)
print("Heroes:", heroes)
print("Empty:", empty_dict)
print("Length of flowers dict:", len(flowers))
Flowers: {1: 'rose', 2: 'lily', 3: 'jasmine'}
Numbers: {1: 5, 3: 7, 8: 6, 9: 4}
Heroes: {'spider': 'man', 'captain': 'america', 'iron': ['tony', 'starks']}
Empty: {}
Length of flowers dict: 3
Using the dict() Constructor
Python also provides the built-in dict() constructor to create dictionaries ?
# Creating dictionary using dict() constructor
colors = dict(red='#FF0000', green='#00FF00', blue='#0000FF')
print("Colors:", colors)
# Converting list of tuples to dictionary
pairs = [('name', 'Alice'), ('age', 25), ('city', 'New York')]
person = dict(pairs)
print("Person:", person)
Colors: {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}
Person: {'name': 'Alice', 'age': 25, 'city': 'New York'}
Special Dictionary Types
Python's collections module provides specialized dictionary types for specific use cases.
OrderedDict
Maintains insertion order (though regular dictionaries now preserve order in Python 3.7+) ?
from collections import OrderedDict
fruits = OrderedDict()
fruits[1] = "apple"
fruits[2] = "mango"
fruits[3] = "cherry"
for key, value in fruits.items():
print(f"{key}: {value}")
1: apple 2: mango 3: cherry
defaultdict
Provides default values for non-existing keys ?
from collections import defaultdict
def default_value():
return "not existing"
grades = defaultdict(default_value)
grades['Alice'] = 'A'
grades['Bob'] = 'B'
print("Alice's grade:", grades['Alice'])
print("Charlie's grade:", grades['Charlie']) # Non-existing key
Alice's grade: A Charlie's grade: not existing
Counter
Counts occurrences of elements ?
from collections import Counter
text = 'an apple a day keeps doctor away'
word_count = Counter(text.split())
print("Word frequencies:")
print(word_count)
print("Most common word:", word_count.most_common(1))
Word frequencies:
Counter({'an': 1, 'apple': 1, 'a': 1, 'day': 1, 'keeps': 1, 'doctor': 1, 'away': 1})
Most common word: [('an', 1)]
Key Features Summary
| Feature | Description | Example |
|---|---|---|
| Keys are unique | No duplicate keys allowed |
{'a': 1, 'a': 2} ? {'a': 2}
|
| Case sensitive | Different cases = different keys |
'Name' ? 'name'
|
| Mixed types | Values can be any data type | {'str': 'text', 'num': 42, 'list': [1,2]} |
Conclusion
Dictionary literals using curly brackets {} provide the most straightforward way to create dictionaries in Python. Use specialized dictionary types from the collections module when you need specific functionality like default values or element counting.
