>>> r
{'Name': 'Ambiorix', 'age': 34}
>>> {r[a]:a for a in r if type(r[a])==int}
{34: 'age'}
>>> {r[a]:a for a in r if type(r[a])==str}
{'Ambiorix': 'Name'}
>>> r
{'Name': 'Ambiorix', 'age': 34}
>>> {r[a]:a for a in r if type(r[a])==int}
{34: 'age'}
>>> {r[a]:a for a in r if type(r[a])==str}
{'Ambiorix': 'Name'}
>>>
>>>
>>> answer
'Ambiorix Rodriguez Placencio'
>>> chr(max({a:ord(a) for a in answer}.values()))
'z'
>>> chr(max({a:ord(a) for a in answer}.values()))
Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection:
# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}
# Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]
# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = statusimport os
import sys
def search_key_value(file_path, search_key):
# Open and read the file safely using a context manager
with open(file_path, 'r') as file:
lines = file.readlines()
# Create a dictionary from the parsed list
parsed_dict = {line.strip().split(',')[0]: line.strip().split(',')[1] for line in lines}
# Return the value associated with the search key if it exists
return parsed_dict.get(search_key)
# Example usage:
file_path = '/var/www/html/fwlist.conf'
sound_folder = '/var/lib/asterisk/sounds/en/custom/'
search_key = sys.argv[1]
file = search_key_value(file_path, search_key)
if file:
print(f"The value for key '{search_key}' is: {file}")
# Check if the corresponding file exists
file_path = sound_folder + file
print(1 if os.path.isfile(file_path) else 0)
else:
print(f"Key '{search_key}' not found.")
print(0)
>>> c
{'Ambiorix': 'Rodriguez', 'Katherine': 'Maria, 'Rosa: 'Perez'}
>>> [a for a in list(c.keys()) if 'k'.lower() in a.lower()]
['Katherine']
>>> [a for a in list(c.values()) if 'R'.lower() in a.lower()]
['Rodriguez']
https://github.com/AssemblyAI-Community/python-realtime-twilio-transcription/blob/main/main.py
try:
n = 10
if n < 20:
raise ValueError("n must be at least 20") # Raising a ValueError with a message
except ValueError as e:
print("An error has occurred:", e)
finally:
print("Code completed.")
--------
Custom Exception error.
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error message.")
except CustomError as e:
print("An error has occurred:", e)
finally:
print("Code completed.")