Lecture 3 Flashcards
dictionaries - defining, creating, accessing, methods for modification + copying of dictionaries
define dictionary
A data structure that consists of key-value pairs.
We use the keys to describe our data and the values to represent the data.
Keys are usually numbers or strings; values can be any data type
strip method syntax+ function
stringname.strip(characters to remove)
removing characters from the beginning or end of a string for characters supplied as arguments
OR
if no argument passed, will remove only leading and trailing spaces in a string
how can you add a key-value pair to a dictionary?
- define dictionary d={}
- d[“key1”] = “value1”
how can you initialize a dictionary using typecasting?
d = dict()
how do you combine 2 lists into a dictionary using iteration and one variable?
- define both lists
- define range + variable
- key-value assignment formatting: d[l1[i]] = l2[i] NOTE brackets around key, none around value. if you add brackets around the value it will print with brackets!*
how do you use a range loop to print ONLY the values in a dictionary?
dictionaryname={}
for i in dictionaryname.values():
print(i)
how do you use a loop to print ONLY the keys in a dictionary?
dictionaryname={}
for i in dictionaryname.keys():
print(i)
how do you use a loop to print the KEY-VALUE PAIRS in a dictionary?
dictionaryname={}
for i in dictionaryname.items():
print(i)
how do you print a LIST of TUPLES containing the key-value pairs in a dictionary?
print(list(dictionaryname.items()))
NOTE: you must typecast to a list or it will auto preface with “dict_items”. will still print a list of tuples
mutability and ordered/unordered? [ ]
[] - mutable and ordered
mutability and ordered/unordered? { }
{} - unordered, mutable, key-value pairs
mutability and ordered/unordered? “ “
”” - ordered, immutable
mutability and ordered/unordered? ( )
() - ordered, immutable
how do you access the values in a dictionary?
using the corresponding keys
update method function and syntax
appends dictionary 2 to the end of dictionary 1. can also pass another iterable object (usually of tuples containing key-value pairs)
dict1.update(dict2)