Last active
October 12, 2021 18:38
-
-
Save mwrites/0d54b050b0f25c4fe16b4bba57e0f66b to your computer and use it in GitHub Desktop.
Python - Dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
phone_book = {"Batman": 468426, | |
"Cersei": 237734, | |
"Ghostbusters": 44678} | |
# ************************ | |
# Enumeration | |
# ************************ | |
for k in phone_book: # give keys | |
# Batman | |
for tuple in phone_book.items(): # give tuples | |
# ('Batman', 468426) | |
# can be simplified to.. | |
for k, v in phone_book.items(): # give key and value | |
# Batman 468426 | |
for index, key in enumerate(phone_book): # enumerate give index and key | |
# 0 Batman | |
for index, (key, value) in enumerate(phone_book.items()): # index, key and value | |
# 0 Batman 468426 | |
# ************************ | |
# Removing | |
# ************************ | |
cersei = phone_book.pop("Cersei") | |
# ************************ | |
# Merge Dicts | |
# ************************ | |
second_phone_book = {"Catwoman": 67423} | |
phone_book.update(second_phone_book) # merged into first dict | |
phone_book = {**phone_book, **second_phone_book} # merged into first dict | |
new_phone_book = {**phone_book, **second_phone_book} # or into a new dict | |
# python 3.9 only | |
d1 |= d2 | |
new_d = d1 | d2 | |
# ************************ | |
# Dictionary Comprehension | |
# ************************ | |
phone_book = {"Batman": 468426, | |
"Cersei": 237734, | |
"Ghostbusters": 44678} | |
uppercased_and_strings_phonebooks = {k.upper(): str(v) for (k, v) in phone_book.items()} | |
# {'BATMAN': '468426', 'CERSEI': '468426', 'GHOSTBUSTERS': '44678'} | |
# ************************ | |
# Conversions from other data structures | |
# ************************ | |
star_wars_list = [ [1,"Anakin"], [2,"Darth Vader"], [3, 1000] ] | |
star_wars_tup = ( (1, "Anakin"), (2, "Darth Vader"), (3, 1000) ) | |
star_wars_set = { (1, "Anakin"), (2, "Darth Vader"), (3, 1000) } | |
star_wars_dict = dict(star_wars_list) | |
star_wars_dict = dict(star_wars_tup) | |
star_wars_dict = dict(star_wars_set) | |
# It works as long as there is a list of tuples, because key value is a tuple | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment