Computer Science
What are different ways of creating dictionaries?
Python Dictionaries
1 Like
Answer
The different ways of creating dictionaries in Python are:
1. By using curly brackets and separating key-value pairs with commas as per the syntax below:
<dictionary-name> = {<key>:<value>, <key>:<value>...} 
For example:
d = {'a': 1, 'b': 2, 'c': 3} 
2. By using dictionary constructor dict(). There are multiple ways to provide keys and values to dict() constructor:
i. Specifying key:value pairs as keyword arguments to dict() function:
For example:
Employee = dict(name = 'john' , salary = 1000, age = 24)
print(Employee)
Output
{'name': 'john', 'salary': 1000, 'age': 24}  
ii. Specifying comma separated key:value pairs:
Key:value pairs are enclosed in curly braces in this format.
For example:
Employee = dict({'name': 'john', 'salary': 1000, 'age': 24})
Output
{'name': 'john', 'salary': 1000, 'age': 24} 
iii. Specifying keys and its corresponding values separately:
Keys and Values are enclosed separately in parentheses and are given as arguments to zip() function.
For example:
Employee = dict(zip(('name','salary','age'),('John',10000,24))) 
Output
{'name': 'John', 'salary': 10000, 'age': 24} 
iv. Specifying key:value pairs separately in form of sequences:
One list or tuple that contains lists/tuples of individual key:value pairs is passed as an argument to dict().
For example:
Employee = dict([['name','John'],['salary',10000],['age',24]]) 
print(Employee)
Output
{'name': 'John', 'salary': 10000, 'age': 24} 
3. By using fromkeys() function:
fromkeys() function is used to create a new dictionary from a sequence containing all the keys and a common value, which will be assigned to all the keys.
For example:
x = ('list', 'set', 'dictionary')
y = 'mutable'
my_dict = dict.fromkeys(x, y)
print(my_dict)
Output
{'list': 'mutable', 'set': 'mutable', 'dictionary': 'mutable'} 
Answered By
2 Likes