반응형
[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
반응형
'프로그래밍 > Python' 카테고리의 다른 글
[python] 폴더 안의 파일들 이름의 공백 또는 - 를 언더바로 변경하는 프로그램 (0) | 2024.08.23 |
---|---|
[python] Working With The Operating System (0) | 2024.08.13 |
[python] 폴더 안의 .webp 이미지를 .png 로 변환 (0) | 2024.08.12 |
[python] 폴더 안의 파일들 이름의 공백 또는 - 를 언더바로 변경하는 프로그램 (0) | 2024.08.12 |
[python] TIOBE Index for August 2024, Python 1st (0) | 2024.08.09 |