DICTIONARIES AND STRUCTURING DATA
• The dictionary data type, provides a flexible way to access and
organize data
• A dictionary is a collection of many values.
• Dictionaries can use many different data types, not just integers.
• Indexes for dictionaries are called keys, and a key with its
associated value is called a key-value pair.
• In code, a dictionary is typed with braces - { }
>>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
• Dictionary’s keys are 'size', 'color', and 'disposition‘ and the values
for these keys are 'fat', 'gray', and 'loud', respectively.
• These values can be accessed through their keys
• Dictionaries can use integer values as keys, but need not have to
start at 0 and can be any number
Dictionaries vs. Lists
1. Items in dictionaries are ordered. 1. Items in lists are ordered.
2. There is no “first” item in a dictionary. 2. The first item in a list is index 0.
3. The order of items does not matter for 3. The order of items matters for
determining whether two dictionaries determining whether two lists are the
are the same same
4. They can be sliced 4. They can be sliced
5. They are useful for associating keys 5. Lists are useful to contain an ordered
with values series of values
Lists and Dictionary
Dictionaries and lists share the following characteristics:
Both are mutable.
Both are dynamic. They can grow and shrink as needed.
Both can be nested. A list can contain another list. A dictionary can contain
another dictionary. A dictionary can also contain a list, and vice versa.
Dictionaries differ from lists primarily in how elements are accessed:
List elements are accessed by their position in the list, via indexing.
Dictionary elements are accessed via keys.
4
Defining a dictionary in python
d={ IPL = {
<key>: <value>, ‘Bengaluru’:
<key>: <value>, ‘RCB’,
. ‘Chennai’: ‘CSK’,
. .
. .
‘Kolkota’: ‘KKR’
<key>: <value>
‘Mumbai’: ‘MI’
} }
5
1. Create an initial dictionary with name and birthday
• Input a name until blank
2. Check if input name is in dictionary by comparing the input name with keys,
3. If matches, access the associated value of the key using square bracket
4. If not, add it using the same square bracket syntax combined with the assignment operator
The keys(), values(), and items() Methods
• There are three dictionary methods that will return list-like values
of the dictionary’s keys, values, or both keys and values: keys(),
values(), and items().
• The values returned by these methods are not true lists: They
cannot be modified and do not have an append() method.
• But these data types (dict_keys, dict_values, and dict_items,
respectively) can be used in for loops.
• Using the keys(), values(), and items() methods, a for loop can
iterate over the keys, values, or key-value pairs in a dictionary,
respectively.
• Also the values in the dict_items value returned by the items()
method are tuples of the key and value.
Accessing keys() and values()
8
>>> spam = {'color': 'red', 'age': 42}
>>> for v in [Link](): • values()- extracts values of
print(v) dictionary.
• Here, a for loop iterates over each
red of the values in the dictionary.
42
• keys() - extracts keys of
>>> for k in [Link]():
print(k)
dictionary
• Here, a for loop iterates over each
color
of the keys in the dictionary.
Age
>>> for i in [Link](): • items() – extracts both key-value
print(i) pairs in the dictionary.
('color', 'red')
('age', 42)
• A true list from one of these >>> spam = {'color': 'red', 'age': 42}
methods can be extracted by >>> [Link]()
passing its list-like return dict_keys(['color', 'age'])
value to the list() function. >>> list([Link]())
['color', 'age']
• The multiple assignment can >>> spam = {'color': 'red', 'age': 42}
>>> for k, v in [Link]():
be used in a for loop to assign
print('Key: ' + k + ' Value: ' + str(v))
the key and value to separate
variables. Key: color Value: red
Key: age Value: 42
Checking Whether a Key or Value Exists in a Dictionary
• The in and not in operators is used to check whether a key or
value exists in a dictionary.
>>> spam = {'name': 'Zophie', 'age': 7}
>>> 'name' in [Link]()
True
>>> 'Zophie' in [Link]()
True
>>> 'color' in [Link]()
False
>>> 'color' not in [Link]()
True
>>> 'color' in spam # shorter version of writing 'color' in [Link]()
False
The get(key , fallback value) Method
• get() method takes two arguments: the key of the value to retrieve
and a fallback value to return if that key does not exist
• Used as an alternative to in and not in, Instead of checking
whether a key exists in a dictionary before accessing that key’s
value
>>> picnicItems = {'apples': 5, 'cups': 2}
>>> 'I am bringing ' + str([Link]('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
>>> 'I am bringing ' + str([Link]('eggs', 0)) + ' eggs.'
'I am bringing 0 eggs.'
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
As of Python version 3.7, dictionaries are ordered.
When we say that dictionaries are ordered, it means that the items have a
defined order, and that order will not change.
Unordered means that the items does not have a defined order, you cannot
refer to an item by using an index.
Dictionaries are changeable, meaning that we can change, add or remove items
after the dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Slicing dictionary in Python
itertools is one of the best modules which helps us to slice dictionaries very easily in python.
The itertools is used to manipulate data structures in python, and it is used to iterate through
different data structures.
This module is very fast, efficient, and easy to use. This module is part of Python’s standard
libraries so you don’t need to install it separately.
Example:
import itertools
student = {'RNo' : 10, 'Marks' : 90, 'Percentage' : 90} Output
new_dict = dict([Link]([Link](), 2))
print(new_dict) {'RNo': 10, 'Marks': 90}
Example:
import itertools
student = {'RNo' : 10, 'Marks' : 90, 'Percentage' : 90}
new_dict = dict([Link]([Link](), 1,3))
print(new_dict)
Output:
{'Marks': 90, 'Percentage': 90}
The setdefault(key,value) Method
• You’ll often have to set a value in a dictionary for a certain key only if
that key does not already have a value. The code looks something like
this:
spam = {'name': 'Pooka', 'age': 5}
if 'color' not in spam:
spam['color'] = 'black'
• The setdefault() method offers this in one line of code.
• The first argument passed to the method is the key to check for, and
the second argument is the value to set at that key if the key does
not exist.
• If the key does exist, the setdefault() method returns the key’s value.
Setdefault when key and its value is present in
dictionary
dict={'name':'pooka','age':26,'color':'white'}
[Link]('color')
dict
Output:
{'name': 'pooka', 'age': 26, 'color': 'white'}
Setdefault when key and its value is not
present in dictionary
dict={'name':'pooka','age':26}
[Link]('color')
dict
Output:
{'name': 'pooka', 'age': 26, 'color': None}
‘color’ not exists, so includes and sets the default value ‘black’ and returns the value
dict={'name':'pooka','age':26}
[Link]('color','black')
print(dict)
Output:
{'name': 'pooka', 'age': 26, 'color': 'black'}
color’ exists, so does not set the default value ‘white’
dict={'name':'pooka','age':26}
[Link]('color','black')
print(dict) Output:
[Link]('color','white') {'name': 'pooka', 'age': 26, 'color': 'black'}
dict {'name': 'pooka', 'age': 26, 'color': 'black'}
What is the output?
What is the output?
dict={'name':'pooka','age':26}
[Link]('color','black') dict={'name':'pooka','age':26}
print(dict) dict['age']
Output: Output
{'name': 'pooka', 'age': 26, 'color': 'black'} 26
Is it possible to extract key using value:
dict={'name':'pooka','age':26}
dict[26]
Output:
KeyError
Is it possible to setdefault for already existing key and its value?
dict={'name':'pooka','age':26,'color':'white'}
[Link]('age',5)
print(dict)
Output:
{'name': 'pooka', 'age': 26, 'color': 'white'}
program that counts the number of occurrences of each letter in a string
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
[Link](character, 0)
count[character] = count[character] + 1
print(count)
Output:
Pretty Printing
• pprint() and pformat() functions “pretty print” a dictionary’s
values by importing the pprint module.
• This is helpful when a cleaner display of the items in a
dictionary is needed than what print() provides.
• If the prettified text is to be obtained as a string value instead
of displaying it on the screen, use [Link]() instead.
• These two lines are equivalent to each other:
[Link](someDictionaryValue)
print([Link](someDictionaryValue))
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
[Link](character, 0)
count[character] = count[character] + 1
[Link](count)
Nested Dictionaries and Lists
• Dictionaries and lists that contain other dictionaries and lists can be used
1. Inside the totalBrought()
function, the for loop iterates
over the keyvalue pairs in
guests
2. Inside the loop, the string of
the guest’s name is assigned to
k, and the dictionary of picnic
items they’re bringing is
assigned to v.
• If the item parameter exists as a
key in this dictionary, it’s value
(the quantity) is added to
numBrought
• If it does not exist as a key, the
get() method returns 0 to be
added to numBrought.
OUTPUT???
Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1
Assignment 5
Read N numbers from the console and create a list. Develop a program to print mean,
variance, and standard deviation with suitable messages.
N = int(input("Enter the number of elements: ")) # Read and create a list
numbers = [int(input("Enter a number: ")) for i in range(N)]
mean = sum(numbers) / N # Calculate mean
variance = sum((x - mean) ** 2 for x in numbers) / N # Calculate variance
standard_deviation = variance ** 0.5 # Calculate standard deviation
print("Mean:", mean)
print("Variance:", variance)
print("Standard Deviation:", standard_deviation)
Read a multi-digit number (as chars) from the console and print the frequency of each digit
number = input("Enter a multi-digit number: ")
# Create a dictionary to store the frequency of each digit
frequency = {str(i): 0 for i in range(10)}
# Iterate over the number and update the frequency of each digit
for char in number:
if [Link]():
frequency[char] += 1
# Print the frequency of each digit with a suitable message
for digit, count in [Link]():
if count > 0:
print(f"Frequency of {digit}: {count}")
How to read nested list?
Output:
list=[]
2
for i in range(0,3): 0
[Link]([]) 1
2
for j in range(0,3): 3
k=int(input()) 4
5
list[i].append(k) 6
print(list) 0
[[2, 0, 1], [2, 3, 4], [5, 6, 0]]