Programming Fundamentals: Tuple and Dictionary
Programming Fundamentals: Tuple and Dictionary
3
Create a tuple from a list
t3 = tuple([2 * x for x in range(1, 5)]) # (2, 4, 6, 8)
You can also create a tuple from a string. Each character in
the string becomes an element in the tuple. For example:
# Create a tuple from a string
t4 = tuple("abac") # t4 is ['a', 'b’,'a', 'c']
You can use the functions len, min, max, and sum on a
tuple. You can use a for loop to traverse all elements in a
tuple, and can access the elements or slices of the elements
using an index operator.
RQ 4
Example:
tuple1 = ("green", "red", "blue") # Create a tuple
print(tuple1)
6
A tuple takes less memory space in Python:
import sys
l = [1,2,3]
t = (1, 2, 3)
print(sys.getsizeof(l))
print(sys.getsizeof(t))
7
Dictionaries
The data structure is called a “dictionary”
because it resembles a word dictionary, where
the words are the keys and the words’
definitions are the values.
A dictionary is a container object that stores a
collection of key/value pairs.
It enables fast retrieval, deletion, and updating
of the value by using the key.
8
A dictionary cannot contain duplicate keys. Each key maps to one value. A
key and its corresponding value form an item (or entry) stored in a dictionary,
as shown in Figure.
Dictionary in Python is an unordered collection of data values, Dictionary
holds key:value pair.
9
Creating dictionary
Create a dictionary by enclosing the items inside a pair
of curly braces {}.
dict1={} #Create an empty dictionary
dict2={1: 'apple', 2: 'ball'} # dictionary with integer
keys
dict3 = {'Name': 'xyz', 1: [1, 2, 3, 4]} #used list in
dictionary
my_dict = {'name':'xyz', 'age': 26} #Accessing Values
in Dictionary
print("value:",my_dict['name’])
print("value:",my_dict.get('age'))
10
#Remove a key from a Python dictionary:
myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict:
del myDict['a’]
print(myDict)
#Sort a Python dictionary by key:
color_dict = {'red':'#FF0000’,
'green':'#008000’,
'black':'#000000’,
'white':'#FFFFFF’}
for key in sorted(color_dict):
print("%s: %s" % (key, color_dict[key]))
11
Program to iterate over dictionaries using for loops:
d = {'x': 10, 'y': 20, 'z': 30}
for dict_key, dict_value in d.items():
print(dict_key,'->',dict_value)
12