Coverts Tuple to List¶
test =('hann', 'matt', 'Eriv')
test
('hann', 'matt', 'Eriv')
tests= list(test)
tests
['hann', 'matt', 'Eriv']
Dictionaries¶
In this lecture you’ll learn how to use Python’s dictionaries, which allow you to connect pieces of related information. You’ll learn how to access the information once it’s in a dictionary and how to modify that information. Because dictionaries can store an almost limitless amount of information, I’ll show you how to loop through the data in a dictionary. Additionally, you’ll learn to nest dictionaries inside lists, lists inside dictionaries, and even dictionaries inside other dictionaries.
Understanding dictionaries allows you to model a variety of real-world objects more accurately. You’ll be able to create a dictionary representing a person and then store as much information as you want about that person. You can store their name, age, location, profession, and any other aspect of a person you can describe. You’ll be able to store any two kinds of information that can be matched up, such as a list of words and their meanings, a list of people’s names and their favorite numbers, a list of mountains and their elevations, and so forth.
A SIMPLE DICTIONARY and Basic function¶
Example 1¶
students= {
'wyu':'faculty',
'zyang':'faculty',
'wma999':'student',
'lwill':'staff'
}
students['wyu']
'faculty'
students['wma999']
'student'
students['zyang']= 'student' #make changes
students
{'wyu': 'faculty', 'zyang': 'student', 'wma999': 'student', 'lwill': 'staff'}
# looking for how many item within the list
len(students)
4
#added new item in the list
students['luke45']= 'student'
students
{'wyu': 'faculty', 'zyang': 'student', 'wma999': 'student', 'lwill': 'staff', 'luke45': 'student'}
#delete an item from the list
del students['wma999']
students
{'wyu': 'faculty', 'zyang': 'student', 'lwill': 'staff', 'luke45': 'student'}
# looking for key item in the dictionaries
students.keys()
dict_keys(['wyu', 'zyang', 'lwill', 'luke45'])
# looking for values
students.values()
dict_values(['faculty', 'student', 'staff', 'student'])
# looking for key and correspond values, return as a list
students.items()
dict_items([('wyu', 'faculty'), ('zyang', 'student'), ('lwill', 'staff'), ('luke45', 'student')])
for student in students.keys():
students[student]=students[student].title()
students
{'wyu': 'Faculty', 'zyang': 'Student', 'lwill': 'Staff', 'luke45': 'Student'}
for student in students: #looping through the key
students[student]=students[student].title()
students
{'wyu': 'Faculty', 'zyang': 'Student', 'lwill': 'Staff', 'luke45': 'Student'}
students= {
'wyu':'faculty',
'zyang':'faculty',
'wma999':'student',
'lwill':'staff'
}
for key, value in students.items():
students[key]= value.title()
students
{'wyu': 'Binghamton Binghamtonfaculty', 'zyang': 'Binghamton Binghamtonstudent', 'lwill': 'Binghamton Binghamtonstaff', 'luke45': 'Binghamton Binghamtonstudent'}
for key, value in students.items():
students[key]= "Binghamton " + value.title()
students
{'wyu': 'Binghamton Faculty', 'zyang': 'Binghamton Faculty', 'wma999': 'Binghamton Student', 'lwill': 'Binghamton Staff'}
employees = {}
employees['zyang99']='staff'
employees
{'zyang99': 'staff'}
Example 2¶
gpa = {
'chen':3.8,
'liu': 3.7,
'Eric':4,
'Wan':4.0
}
gpa
{'chen': 3.8, 'liu': 3.7, 'Eric': 4, 'Wan': 4.0}
gpa['liu']
3.7
Example 3¶
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original position: {alien_0['x_position']}")
# Move the alien to the right.
# Determine how far to move the alien based on its current speed.
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
# This must be a fast alien.
x_increment = 3
# The new position is the old position plus the increment.
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(f"New position: {alien_0['x_position']}")
Original position: 0 New position: 2
LOOPING THROUGH A DICTIONARY¶
A single Python dictionary can contain just a few key-value pairs or millions of pairs. Because a dictionary can contain large amounts of data, Python lets you loop through a dictionary. Dictionaries can be used to store information in a variety of ways; therefore, several different ways exist to loop through them. You can loop through all of a dictionary’s key-value pairs, through its keys, or through its values.
Looping Through All Key-Value Pairs¶
Before we explore the different approaches to looping, let’s consider a new dictionary designed to store information about a user on a website. The following dictionary would store one person’s username, first name, and last name:
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print(f"\nKey: {key}")
print(f"Value: {value}")
Key: username Value: efermi Key: first Value: enrico Key: last Value: fermi
As shown above, to write a for loop for a dictionary, you create names for the two variables that will hold the key and value in each key-value pair. You can choose any names you want for these two variables. This code would work just as well if you had used abbreviations for the variable names, like this:
for k, v in user_0.items()
Looping Through All the Keys in a Dictionary¶
The keys() method is useful when you don’t need to work with all of the values in a dictionary. Let’s loop through the favorite_languages dictionary and print the names of everyone who took the poll:
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
print(name.title())
Jen Sarah Edward Phil
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
if 'erin' not in favorite_languages.keys(): #same with list
print("Erin, please take our poll!")
Erin, please take our poll!
Looping Through a Dictionary’s Keys in a Particular Order¶
Starting in Python 3.7, looping through a dictionary returns the items in the same order they were inserted. Sometimes, though, you’ll want to loop through a dictionary in a different order.
One way to do this is to sort the keys as they’re returned in the for loop. You can use the sorted() function to get a copy of the keys in order:
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages):
print(f"{name.title()}, thank you for taking the poll.")
Edward, thank you for taking the poll. Jen, thank you for taking the poll. Phil, thank you for taking the poll. Sarah, thank you for taking the poll.
Looping Through All Values in a Dictionary¶
If you are primarily interested in the values that a dictionary contains, you can use the values() method to return a list of values without any keys. For example, say we simply want a list of all languages chosen in our programming language poll without the name of the person who chose each language:
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
The following languages have been mentioned: Python C Ruby Python
This approach pulls all the values from the dictionary without checking for repeats. That might work fine with a small number of values, but in a poll with a large number of respondents, this would result in a very repetitive list. To see each language chosen without repetition, we can use a set. A set is a collection in which each item must be unique:
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
The following languages have been mentioned: C Python Ruby
When you wrap set() around a list that contains duplicate items, Python identifies the unique items in the list and builds a set from those items. We use set() to pull out the unique languages in favorite_languages.values().
NESTING¶
Sometimes you’ll want to store multiple dictionaries in a list, or a list of items as a value in a dictionary. This is called nesting. You can nest dictionaries inside a list, a list of items inside a dictionary, or even a dictionary inside another dictionary. Nesting is a powerful feature, as the following examples will demonstrate.
A List of Dictionaries¶
The alien_0 dictionary contains a variety of information about one alien, but it has no room to store information about a second alien, much less a screen full of aliens. How can you manage a fleet of aliens? One way is to make a list of aliens in which each alien is a dictionary of information about that alien. For example, the following code builds a list of three aliens:
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
{'color': 'green', 'points': 5} {'color': 'yellow', 'points': 10} {'color': 'red', 'points': 15}
# Make an empty list for storing aliens.
aliens = []
# Make 30 green aliens.
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# Show the first 5 aliens.
for alien in aliens[:5]:
print(alien)
print("...")
# Show how many aliens have been created.
print(f"Total number of aliens: {len(aliens)}")
{'color': 'green', 'points': 5, 'speed': 'slow'} ... {'color': 'green', 'points': 5, 'speed': 'slow'} ... {'color': 'green', 'points': 5, 'speed': 'slow'} ... {'color': 'green', 'points': 5, 'speed': 'slow'} ... {'color': 'green', 'points': 5, 'speed': 'slow'} ... Total number of aliens: 30
It’s common to store a number of dictionaries in a list when each dictionary contains many kinds of information about one object. For example, you might create a dictionary for each user on a website. All of the dictionaries in the list should have an identical structure so you can loop through the list and work with each dictionary object in the same way.
A List in a Dictionary¶
Rather than putting a dictionary inside a list, it’s sometimes useful to put a list inside a dictionary. For example, consider how you might describe a pizza that someone is ordering. If you were to use only a list, all you could really store is a list of the pizza’s toppings. With a dictionary, a list of toppings can be just one aspect of the pizza you’re describing.
In the following example, two kinds of information are stored for each pizza: a type of crust and a list of toppings. The list of toppings is a value associated with the key 'toppings'. To use the items in the list, we give the name of the dictionary and the key 'toppings', as we would any value in the dictionary. Instead of returning a single value, we get a list of toppings:
avorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print(f"\n{name.title()}'s favorite languages are:")
for language in languages:
print(f"\t{language.title()}")
Jen's favorite languages are: P Y T H O N Sarah's favorite languages are: C Edward's favorite languages are: R U B Y Phil's favorite languages are: P Y T H O N
A Dictionary in a Dictionary¶
You can nest a dictionary inside another dictionary, but your code can get complicated quickly when you do. For example, if you have several users for a website, each with a unique username, you can use the usernames as the keys in a dictionary. You can then store information about each user by using a dictionary as the value associated with their username. In the following listing, we store three pieces of information about each user: their first name, last name, and location. We’ll access this information by looping through the usernames and the dictionary of information associated with each username:
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print(f"\nUsername: {username}")
full_name = f"{user_info['first']} {user_info['last']}"
location = user_info['location']
print(f"\tFull name: {full_name.title()}")
print(f"\tLocation: {location.title()}")
Username: aeinstein Full name: Albert Einstein Location: Princeton Username: mcurie Full name: Marie Curie Location: Paris
Example 1 Continue¶
students= {
'wyu':{'name':'Wanh','type':'faculty','department':'Geography', 'age':18},
'zyang':'faculty',
'wma999':'student',
'lwill':'staff'
}
students['wyu']['department']
'Geography'
students['zyang']['department']
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[38], line 1 ----> 1 students['zyang']['department'] TypeError: string indices must be integers
students= {
'wyu':{'name':'Wanh','type':'faculty','department':'Geography', 'age':18,
"address":{
'street': '4400 Parkway E',
'city':'Vestal',
'state':'NY',
'zip': 13850
}},
'zyang':['Zhanchao', 'student','envi', 19],
'wma999':'student',
'lwill':'staff'
}
students['zyang'][2]
'envi'
students= {
'wyu':{'name':'Wanh','type':'faculty','department':'Geography', 'age':18,
"address":{
'street': '4400 Parkway E',
'city':'Vestal',
'state':'NY',
'zip': 13850
}},
'zyang':['Zhanchao', 'student','envi', 19],
'wma999':'student',
'lwill':'staff'
}
students['wyu']["address"]['zip']
13850
# case sensitive . if doesn't match it will run into error (case sensitive)
students['wyu']["address"]['Zip']
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[54], line 2 1 # case sensitive . if doesn't match it will run into error (case sensitive) ----> 2 students['wyu']["address"]['Zip'] KeyError: 'Zip'
# 'get' function can avoid run into error, but it can be None
students['wyu']["address"].get('Zip')
students['wyu']["address"].get('Zip') is None
True
# allow computer give users a message if not exisit
students['wyu']["address"].get('Zip', 'This item does not exist in the database')
'This item does not exist in the database'
students['wyu']["address"].get('zip', 'This item does not exist in the database')
13850
SUMMARY¶
In this chapter you learned how to define a dictionary and how to work with the information stored in a dictionary. You learned how to access and modify individual elements in a dictionary, and how to loop through all of the information in a dictionary. You learned to loop through a dictionary’s key-value pairs, its keys, and its values. You also learned how to nest multiple dictionaries in a list, nest lists in a dictionary, and nest a dictionary inside a dictionary.|
References¶
- Matthes, Eric (2022). Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming. No Starch Press. ISBN: 978-1593279288. (Publisher website)
- Dr.Qiusheng Wu Online lecture from Youtube