Tuples, Dictionaries

decal·2023년 1월 5일
0

study notes

목록 보기
5/12

I am currently on chapter 10 on Mimo: Python

  • List []
  • Tuples ()
  • Dictionaries {}

Elements in Tuples cannot be edited (can't add, delete)
-> If editing is needed, use list instead

Use dictionaries to associate each value of a collection with a meaningful "label", instead of an index

For example:

car_data = {
 "brand": "Cadillac",
 "year": 1960,
 "restoration": 1988
}

print(car_data)

-> "brand" & "Cardillac" are key-value pairs

We can access dictionary values by their key like the following:

actor_bio = {
 "name": "Bill Murray",
 "known for": ["Lost in Translation", "Rushmore"]
}

print(actor_bio["name"])

After accessing the value, we can store it in a variable.

The variable "player" stands for the keys in the following:
(and the output in the console would be just the scores)

player_scores = {
 "ann": 13,
 "michael": 20,
 "ava": 34
}

for player in player_scores:
  print(player_scores[player])

To change the value, we first access the current value associated with the key (NOT by the index), and then enter new value like the following:

ticket = {
 "seat no.": 25,
 "first class": False
}

ticket["first class"] = True 
print(ticket)

To store the value of the key, create the variable like the following:

participants = {
  "Meg": True,
  "Kim": False,
  "Luis": True,
  "Luis M.": False
}

meg = participants["Meg"]
print(meg)

To add a key, code a dictionary and then the new key's name like the following:

ticket = {
 "seat no.": 25
}

ticket["window"]

And add the value next to the key like the following:

ticket = {
 "seat no.": 25
}

ticket["window"] = True

'in' keyword lets us check whether a dictionary contains certain key by giving 'True' or 'False (as with lists)

personal_data = {
 "name": "Mac Miller",
 "telephone": "0047865791"
}
print("name" in personal_data)
print("address" in personal_data)

output:
True
False

and you can store that as a variable like the following:

personal_data = {
 "name": "Mac Miller",
 "telephone": "0047865791"
}

has_age = "age" in personal_data
print(has_age)

output: False

.pop() removes the key-value set in dictionaries (similarly to removing elements in a list)

ticket = {
 "seat no.": 25,
 "window": True
}

ticket.pop("window")
print(ticket)

output: {"seat no.": 25}

Since attempting to remove a key that does not exist gives an error, it is better to check if there is certain key with 'in':

ticket = {
 "seat no.": 25,
 "window": True
}

if "destination" in ticket:
  ticket.pop("destination")

print(ticket)

output: {'seat no.': 25, 'window': True}

You can remove the key but store the corresponding value by creating a variable:

scoops = {
  "vanilla": 1,
  "chocolate": 2,
  "hazelnut": 1
}

vanilla = scoops.pop("vanilla")  
print(vanilla)

output: 1

0개의 댓글