Lists and Dictionaries: Difference between revisions
Appearance
No edit summary |
No edit summary |
||
(27 intermediate revisions by one other user not shown) | |||
Line 1: | Line 1: | ||
This page is a cheatsheet for using lists and dictionaries in [[Python]]. | |||
{| class="wikitable" | |||
|+ Caption text | |||
|- | |||
! Header text !! Lists !! Dictionaries !! Dictionary in List !! List in Dictionary in List | |||
|- | |||
| Create || <syntaxhighlight lang="Python" line>x = [1, 2]</syntaxhighlight>|| <syntaxhighlight lang="Python" line>x = { | |||
'a': 2, | |||
'b': 3, | |||
}</syntaxhighlight> || <syntaxhighlight lang="Python" line>x = [1, | |||
{ | |||
'a': 2, | |||
'b': 3, | |||
} | |||
]</syntaxhighlight> || <syntaxhighlight lang="Python" line> x = [1, | |||
{ | |||
'a': 2, | |||
'b': [3, 4], | |||
} | |||
] | |||
</syntaxhighlight> | |||
|- | |||
| Retrieve || <syntaxhighlight lang="Python" line>x[1]</syntaxhighlight> || <syntaxhighlight lang="Python" line>x['b']</syntaxhighlight> || <syntaxhighlight lang="Python" line>x[1]['b']</syntaxhighlight> || <syntaxhighlight lang="Python" line>x[1]['b][1]</syntaxhighlight> | |||
|- | |||
| Example || Example || Example || Example || Example | |||
|} | |||
== Lists == | == Lists == | ||
Create a list | Create a list | ||
<syntaxhighlight lang=" | <syntaxhighlight lang="Python" line> | ||
people = [] # empty list | people = [] # empty list | ||
animals = ['daisy','pat','wabbit','bunny'] | animals = ['daisy','pat','wabbit','bunny'] | ||
Line 9: | Line 36: | ||
Access elements | Access elements | ||
<syntaxhighlight lang=" | <syntaxhighlight lang="Python" line> | ||
print(animals[0]) # first item | print(animals[0]) # first item | ||
print(animals[-1]) # last item | print(animals[-1]) # last item | ||
Line 110: | Line 137: | ||
1 in numbers and 4 in numbers # returns false | 1 in numbers and 4 in numbers # returns false | ||
4 not in numbers # returns true | 4 not in numbers # returns true | ||
</syntaxhighlight> | |||
If Statements | |||
<syntaxhighlight lang="python" line> | |||
age = 18 | |||
if age >= 18: # use a colon like a for list | |||
print(f"At age {age}, you can drive.") | |||
elif age = 17: # one or more optional | |||
print("Next year!") | |||
else: # optional | |||
print(f"{age} is too young!") | |||
numbers = list(range(0,11)) | |||
print(numbers) | |||
if numbers: # is there anything in numbers? | |||
for number in numbers: | |||
if number == 0: | |||
print(f"{number} is nothing at all!") | |||
elif number % 2: | |||
print(f"{number} is an even number.") | |||
else: | |||
print(f"{number} is an odd number.") | |||
else: | |||
print("No numbers!") | |||
</syntaxhighlight> | |||
Check a list against a list | |||
<syntaxhighlight lang="python" line> | |||
library_books = ["Gravity's Rainbow", "Naked Lunch", | |||
"Hopscotch", "Crash"] | |||
orders = ["Gravity's Rainbow", "The Soft Machine", | |||
"Hopscotch", "The Atrocity Exhibition"] | |||
for order in orders: | |||
if order in library_books: | |||
print(f"{order} added to package.") | |||
else: | |||
print(f"Sorry, we don't have {order}.") | |||
</syntaxhighlight> | |||
== Dictionaries == | |||
Create a dictionary | |||
<syntaxhighlight lang="python" line> | |||
book_0 = {} # create empty dictionary | |||
book_1 = { | |||
"title": "Gravity's Rainbow", | |||
"author": "Thomas Pynchon"} # create dictionary with key-value pairs | |||
book_1["pub_date"] = "1973" # add key-value pair | |||
book_1["pages"] = "750 odd" | |||
book_1["pages"] = "776" # if key exists, update value | |||
del book_1["pages"] # delete key-value pair | |||
print(book_1) | |||
print(f"{book_1['title']} was written by {book_1['author']} in {book_1['pub_date']}.") | |||
pages = book_1.get('pages', 'Not Available') | |||
print(pages) | |||
</syntaxhighlight> | |||
Loop Through a Dictionary | |||
<syntaxhighlight lang="python" line> | |||
author_0 = { | |||
'first_name': 'Thomas', | |||
'last_name': 'Pynchon', | |||
'birth_date': '1937', | |||
} | |||
for key, value in author_0.items(): # items() gets both keys and values | |||
print(f"Key: {key}, Value: {value}") | |||
for k in author_0.keys(): # keys() gets just the keys | |||
print(f"{k}") | |||
for v in author_0.values(): # values() gets just the values | |||
print(f"{v}") | |||
</syntaxhighlight> | |||
Nest Dictionaries in a List and Lists in a Dictionary | |||
<syntaxhighlight lang="python" line> | |||
author_0 = { # each author is a dictionary | |||
'first_name': 'Thomas', | |||
'last_name': 'Pynchon', | |||
'books': [ # the books key contains a list | |||
"V", | |||
"Gravity's Rainbow", | |||
"The Crying of Lot 49", | |||
] | |||
} | |||
author_1 = { | |||
'first_name': 'William', | |||
'last_name': 'Burroughs', | |||
'books': [ | |||
"Naked Lunch", | |||
"The Soft Machine", | |||
"The Ticket That Exploded", | |||
] | |||
} | |||
author_2 = { | |||
'first_name': 'JG', | |||
'last_name': 'Ballard', | |||
'books': [ | |||
"The Drowned World", | |||
"Crash", | |||
"Concrete Island", | |||
] | |||
} | |||
authors = [author_0, author_1, author_2] # authors is a list of the dictionaries | |||
print(authors[1]) # print the 2nd dictionary in the list | |||
print(authors[1]['last_name']) # print the 'last_name' of the 2nd dictionary in the list | |||
print(authors[1]['books'][2]) # print the third 'book' of the 2nd dictionary in the list | |||
for author in authors: # loop over the authors list | |||
author_books = "" | |||
for book in author['books']: # loop over the books list | |||
author_books += book + ", " | |||
author_books = author_books.removesuffix(', ') # remove the trailing comma | |||
print(f"{author['last_name']} wrote {author_books}.") | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="python" line> | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="python" line> | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="python" line> | |||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="python" line> | <syntaxhighlight lang="python" line> | ||
Line 120: | Line 273: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
[[Category:Python]] |
Latest revision as of 17:45, 16 February 2025
This page is a cheatsheet for using lists and dictionaries in Python.
Header text | Lists | Dictionaries | Dictionary in List | List in Dictionary in List |
---|---|---|---|---|
Create |
|
|
|
|
Retrieve |
|
|
|
|
Example | Example | Example | Example | Example |
Lists
Create a list
people = [] # empty list
animals = ['daisy','pat','wabbit','bunny']
Access elements
print(animals[0]) # first item
print(animals[-1]) # last item
print(animals[-2]) # penultimate item
print(f"{animals[0].title()} is a cow.") # in an f-string
Modify, add, insert elements
animals[3] = 'veau' # replace item 3
animals.append('croc') # add new item to end of list
animals.insert(1,'pato') # insert item at index 1
Remove elements
del animals[0] # delete item at index 0
popped_animal = animals.pop() # remove last item
popped_animal = animals.pop(2) # remove item at index 2
animals.remove('veau') # remove (first instance of) item by value
Organize Lists
animals.sort() # sort values a-z
animals.sort(reverse=True) # sort values z-a
animals.reverse() # reverse order (not z-a)
print(sorted(animals)) # temporarily sort
len(animals) # returns number of items
Loop on a List
for animal in animals: # for loop requires a colon
print(animal) # indent each line in the loop
print(f"Hello {animal.title()}")
print(f"We have {len(animals)} animals!") # stop indenting after the loop
Create a list of numbers and list statistics
numbers = list(range(1,11)) # list function makes a list, range function creates 1-10
odd_numbers = list(range(1, 11, 2)) #third parameter is step
even_numbers = list(range(2, 11, 2))
square_numbers = []
for value in range(1, 11):
square_numbers.append(value ** 2)
print(square_numbers)
square_nos = [value ** 2 for value in range(1, 11)] # list comprehension
print(square_nos)
print(min(square_nos))
print(max(square_nos))
print(sum(square_nos))
Slice a list
print(square_nos[0:3]) # first three
print(square_nos[2:6]) # 3rd, 4th, 5th, 6th
print(square_nos[:5]) # first five
print(square_nos[5:]) # from 5th to end
print(square_nos[-3:]) # last three
print(square_nos[0:5:2]) # first five, step 2
for number in square_nos[::3]: # every 3rd number of entire list
print(number)
Copy a list
new_squares = square_nos # new list is linked to old one
new_squares = square_nos[:] # creates a new, separate list
Tuples
Tuples are immutable lists. You cannot modify values in a tuple, but you can replace the entire tuple.
limits = (10, 20) # defines the tuple
limits = (10, 30) # redefines the tuple
If Statements
Conditional Tests
number = 1
number == 1 # returns True
number == 2 # returns False
number != 2 # returns True (because 1 is not equal to 2)
number < 2 # returns True
number > 2 # returns False
letter = A
number = 2 and letter = A # returns false as only one condition is true
number = 2 or letter = A # returns true as one condition is true
numbers =[1, 2, 3]
1 in numbers # returns true
1 in numbers and 4 in numbers # returns false
4 not in numbers # returns true
If Statements
age = 18
if age >= 18: # use a colon like a for list
print(f"At age {age}, you can drive.")
elif age = 17: # one or more optional
print("Next year!")
else: # optional
print(f"{age} is too young!")
numbers = list(range(0,11))
print(numbers)
if numbers: # is there anything in numbers?
for number in numbers:
if number == 0:
print(f"{number} is nothing at all!")
elif number % 2:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.")
else:
print("No numbers!")
Check a list against a list
library_books = ["Gravity's Rainbow", "Naked Lunch",
"Hopscotch", "Crash"]
orders = ["Gravity's Rainbow", "The Soft Machine",
"Hopscotch", "The Atrocity Exhibition"]
for order in orders:
if order in library_books:
print(f"{order} added to package.")
else:
print(f"Sorry, we don't have {order}.")
Dictionaries
Create a dictionary
book_0 = {} # create empty dictionary
book_1 = {
"title": "Gravity's Rainbow",
"author": "Thomas Pynchon"} # create dictionary with key-value pairs
book_1["pub_date"] = "1973" # add key-value pair
book_1["pages"] = "750 odd"
book_1["pages"] = "776" # if key exists, update value
del book_1["pages"] # delete key-value pair
print(book_1)
print(f"{book_1['title']} was written by {book_1['author']} in {book_1['pub_date']}.")
pages = book_1.get('pages', 'Not Available')
print(pages)
Loop Through a Dictionary
author_0 = {
'first_name': 'Thomas',
'last_name': 'Pynchon',
'birth_date': '1937',
}
for key, value in author_0.items(): # items() gets both keys and values
print(f"Key: {key}, Value: {value}")
for k in author_0.keys(): # keys() gets just the keys
print(f"{k}")
for v in author_0.values(): # values() gets just the values
print(f"{v}")
Nest Dictionaries in a List and Lists in a Dictionary
author_0 = { # each author is a dictionary
'first_name': 'Thomas',
'last_name': 'Pynchon',
'books': [ # the books key contains a list
"V",
"Gravity's Rainbow",
"The Crying of Lot 49",
]
}
author_1 = {
'first_name': 'William',
'last_name': 'Burroughs',
'books': [
"Naked Lunch",
"The Soft Machine",
"The Ticket That Exploded",
]
}
author_2 = {
'first_name': 'JG',
'last_name': 'Ballard',
'books': [
"The Drowned World",
"Crash",
"Concrete Island",
]
}
authors = [author_0, author_1, author_2] # authors is a list of the dictionaries
print(authors[1]) # print the 2nd dictionary in the list
print(authors[1]['last_name']) # print the 'last_name' of the 2nd dictionary in the list
print(authors[1]['books'][2]) # print the third 'book' of the 2nd dictionary in the list
for author in authors: # loop over the authors list
author_books = ""
for book in author['books']: # loop over the books list
author_books += book + ", "
author_books = author_books.removesuffix(', ') # remove the trailing comma
print(f"{author['last_name']} wrote {author_books}.")