Introduction to Python Flashcards
Name = {key: value, key: value}
Dictionary
dictionary[key] = value
How to add an item to a dictionary or overwrite an existing value
dictionary.update({key:value, key:value })
Add multiple items to a dictionary at once
Py: How to overwrite an existing value associated to a key in a dictionary
Using the single add method to a key with the same name will overwrite it.
dictionary[key] = value
dictionary = {key: value for key, value in zip(varkey, varvalue)}
Create a dictionary using comprehension
zip(iterator1a, iterator2a, …)
Takes multiple iterators (list) inputs and returns as a single list of tuples
my_dict.get(key)
How to safely retrieve a key from a dictionary (won’t return an error if not there)
Can add an optional default return value if not in the dictionary by (key, value)
my_dict.pop(key, default return)
Safely checked for key and removes from dictionary if true. Default return is optional
list(my_dict)
Returns a list of all dictionary keys
my_dict.keys()
Can be used (And by iteration) to return a viewable (list) key objects
my _dict.values()
Return a list of values much like dict_keys
my_dict.items()
.keys() and .values() combined returning elements of tuples
with open(‘your doc.txt’) as a_doc:
some_contents = a_doc.read()
print(some_contents)
Print contents of a text file
with open(‘your doc.txt’) as a_doc:
for line in a_doc.readlines ():
print(line)
Print a single line from a text doc
with open(‘your doc.txt’) as a_doc:
first_line = a_doc.readline ()
second _line = a_doc.readline()
print(second_line)
Extract just a single line from