0% found this document useful (0 votes)
20 views2 pages

Dictionary 114722

Uploaded by

pammia243
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views2 pages

Dictionary 114722

Uploaded by

pammia243
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Dictionary

Dictionary is a data structure in which we store values as a pair of key and value. Each key is separated
from its value by a colon (:), and consecutive items are separated by commas. The entire items in a
dictionary are enclosed in curly brackets “{}”.

• Duplicate keys are not allowed but values can be duplicate.


• Heterogeneous objects are allowed for both keys and values.
• Dictionaries are mutable.
• Dictionaries are dynamic.
• Indexing and slicing concepts are not applicable.
Note: Dictionary keys are case-sensitive. Two keys with the same name but in different case are not the
same in python.
Syntax:
dictionary_name = {key_1 : value_1, key_2 : value_2, key_3 : value_3}
Creating a dictionary:

• To create an empty dictionary, just write the following line of code


d = {} or d = dict()
Output: {}
• A dictionary can also be created by specifying key_value pairs separated by a colon in curly
brackets as shown below.
Example:
d = {"Name" : "John", "Roll_no" : 45, "class" : "B.Tech"}
print(d)
Output: {'Name': 'John', 'Roll_no': 45, 'class': 'B.Tech'}

• To create a dictionary with one or more key_value pairs you can also use the dict() function. The
dict() creates a dictionary directly from a sequence of key value pairs.
Example:
d = dict([("Name", "John"), ("Roll_no", 45), ("class", "B.Tech")])
print(d)
Output: {'Name': 'John', 'Roll_no': 45, 'class': 'B.Tech'}

• A dictionary comprehension is a syntactic construct which creates a dictionary based on existing


dictionary.
Syntax:
d = {expression for variable in sequence [if condition]}
Example: Program to create 10 key-value pairs where key is a number in the range 1-10 and the
value is twice the number.
d = {x : 2*x for x in range(1,10)}
print(d)
Output: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
Accessing Values:
To access values in a dictionary, square brackets are used along with the key to obtain its value.
Example:
d = {"Name" : "John", "Roll_no" : 45, "class" : "B.Tech"}
print(d["Name"])
print(d["Roll_no"])
Output: John
45
Note: If the specified key is not available in the dictionary, a keyError is generated.
Example:
d = {"Name" : "John", "Roll_no" : 45, "class" : "B.Tech"}
print(d["Subject"])

Output: KeyError: 'Subject'

print(d["John"])
Output: KeyError: 'John'

You might also like