Skip to content

Instantly share code, notes, and snippets.

@IvanFrecia
Created April 30, 2021 00:49
Show Gist options
  • Save IvanFrecia/fd82d19772e0ce6177f9f7df26d0bc1a to your computer and use it in GitHub Desktop.
Save IvanFrecia/fd82d19772e0ce6177f9f7df26d0bc1a to your computer and use it in GitHub Desktop.
13.3.3. The Pythonic Way to Enumerate Items in a Sequence
# 1) With only one line of code, assign the variables water, fire, electric, and grass to the values
# “Squirtle”, “Charmander”, “Pikachu”, and “Bulbasaur”
water, fire, electric, grass = "Squirtle", "Charmander", "Pikachu", "Bulbasaur"
# 2) With only one line of code, assign four variables, v1, v2, v3, and v4, to the following four values: 1, 2, 3, 4.
v1, v2, v3, v4 = 1, 2, 3, 4
# 3) If you remember, the .items() dictionary method produces a sequence of tuples.
# Keeping this in mind, we have provided you a dictionary called pokemon.
# For every key value pair, append the key to the list p_names, and append the value to the list p_number.
# Do not use the .keys() or .values() methods.
pokemon = {'Rattata': 19, 'Machop': 66, 'Seel': 86, 'Volbeat': 86, 'Solrock': 126}
p_names = []
p_number = []
for k, v in pokemon.items():
p_names.append(k)
p_number.append(v)
# 4) The .items() method produces a sequence of key-value pair tuples. With this in mind,
# write code to create a list of keys from the dictionary track_medal_counts and assign the
# list to the variable name track_events. Do NOT use the .keys() method
track_medal_counts = {'shot put': 1, 'long jump': 3, '100 meters': 2, '400 meters': 2, '100 meter hurdles': 3, 'triple jump': 3, 'steeplechase': 2, '1500 meters': 1, '5K': 0, '10K': 0, 'marathon': 0, '200 meters': 0, '400 meter hurdles': 0, 'high jump': 1}
track_events = []
for kv in track_medal_counts.items():
track_events.append(kv[0])
@hadrocodium
Copy link

hadrocodium commented Apr 2, 2022

"""
The .items() method produces a sequence of key-value pair tuples. With this in mind, write code to create a list of keys from the dictionary track_medal_counts and assign the list to the variable name track_events. Do NOT use the .keys() method.
"""


track_medal_counts = {'shot put': 1, 'long jump': 3, '100 meters': 2, '400 meters': 2, '100 meter hurdles': 3, 'triple jump': 3, 'steeplechase': 2, '1500 meters': 1, '5K': 0, '10K': 0, 'marathon': 0, '200 meters': 0, '400 meter hurdles': 0, 'high jump': 1}

# tup_key_value_pair is tuple because items method produces the tuples in which the first element is key, and the second element is value
track_events = [tup_key_value_pair[0] for tup_key_value_pair in track_medal_counts.items()]

print(track_events)
  

tup_key_value_pair[0] gets key from key-value tuple.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment