[python] Working With Dictionaries

[python] Working With Dictionaries

1. Creating a Dictionary

To forge a new dictionary:

# A tome of elements and their symbols
elements = {'Hydrogen': 'H', 'Helium': 'He', 'Lithium': 'Li'}

2. Adding or Updating Entries

To add a new entry or update an existing one:

elements['Carbon'] = 'C'  # Adds 'Carbon' or updates its value to 'C'

3. Removing an Entry

To banish an entry from the dictionary:

del elements['Lithium']  # Removes the key 'Lithium' and its value

4. Checking for Key Existence

To check if a key resides within the dictionary:

if 'Helium' in elements:
    print('Helium is present')

5. Iterating Over Keys

To iterate over the keys in the dictionary:

for element in elements:
    print(element)  # Prints each key

6. Iterating Over Values

To traverse through the values in the dictionary:

for symbol in elements.values():
    print(symbol)  # Prints each value

7. Iterating Over Items

To journey through both keys and values together:

for element, symbol in elements.items():
    print(f'{element}: {symbol}')

8. Dictionary Comprehension

To conjure a new dictionary through an incantation over an iterable:

# Squares of numbers from 0 to 4
squares = {x: x**2 for x in range(5)}

9. Merging Dictionaries

To merge two or more dictionaries, forming a new alliance of their entries:

alchemists = {'Paracelsus': 'Mercury'}
philosophers = {'Plato': 'Aether'}
merged = {**alchemists, **philosophers}  # Python 3.5+

10. Getting a Value with Default

To retrieve a value safely, providing a default for absent keys:

element = elements.get('Neon', 'Unknown')  # Returns 'Unknown' if 'Neon' is not found

 

https://blog.stackademic.com/ultimate-python-cheat-sheet-practical-python-for-everyday-tasks-c267c1394ee8

 

Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks

(My Other Ultimate Guides)

blog.stackademic.com