Working with Dictionaries and Sets Flashcards
Question: Consider a dictionary of names and ages set up as below:
Code Editor:
names_ages = {‘John’: 35, ‘Jim’: 45, ‘Alice’: 25}
How would you look up Alice’s age in this dictionary?
names_ages[‘Alice’]
A set in Python can contain which of the following data types?
Floats
Strings
Tuples
Dictionaries
Lists
A set in python contains
Floats
Strings
Tuples
it cannot contain dictionary, Lists
Question: Consider a nested list of names and ages:
Code Editor:
names_ages = [[‘John’, 35], [‘Jill’, 38], [‘Tim’, 27]]
How would you convert this to a dictionary with names as the keys and ages as values?
dict(names_ages)
Question: Consider a nested list of names and ages:
Code Editor:
names_ages = [[‘John’, 35], [‘Jill’, 38], [‘Tim’, 27]]
How would you access Tim’s age in this nested list?
names_ages[2][1]
set_1 = {2, 4, 6, 8}
set_2 = {1, 2, 5, 6, 7, 8}
What operation would I run to get a result set with all of the elements from both sets?
set_1.union(set_2)
Code Editor:
names_ages = {‘John’: 35, ‘Jim’: 45, ‘Alice’: 25}
and a second dictionary as below:
Code Editor:
updated_names_ages = {‘Ella’: 29, ‘John’: 36}
How would you update the names_ages dictionary with the values in updated_names_ages dictionary?
names_ages.update(updated_names_ages)
names_ages = {‘John’: 35, ‘Jim’: 45, ‘Alice’: 25}
What would the output be if you were to run this code?
names_ages[‘Tim’]
KeyError: ‘Tim’
set
you canot add list,dictionary to set
you can add tuple,strings and floats to set