Używam Python słowniki v2.7, zagnieżdżona wewnątrz jednego innego tak:Jak zainicjować zagnieżdżonych słowniki w Pythonie
def example(format_str, year, value):
format_to_year_to_value_dict = {}
# In the actual code there are many format_str and year values,
# not just the one inserted here.
if not format_str in format_to_year_to_value_dict:
format_to_year_to_value_dict[format_str] = {}
format_to_year_to_value_dict[format_str][year] = value
Wydaje się nieco niezdarny zainicjować słownika pierwszego stopnia z pustym przed słowniku wstawiony do słownika drugiego poziomu. Czy istnieje sposób na ustawienie wartości przy jednoczesnym tworzeniu słownika na pierwszym poziomie, jeśli już go nie ma? Wyobrażam sobie coś takiego, aby uniknąć inicjator Warunkowo:
def example(format_str, year, value):
format_to_year_to_value_dict = {}
add_dict_value(format_to_year_to_value_dict[format_str], year, value)
Ponadto, co jeśli wewnętrzna DICT powinna sama zainicjować na liście?
def example(format_str, year, value):
format_to_year_to_value_dict = {}
# In the actual code there are many format_str and year values,
# not just the one inserted here.
if not format_str in format_to_year_to_value_dict:
format_to_year_to_value_dict[format_str] = {}
if not year in format_to_year_to_value_dict[format_str]:
format_to_year_to_value_dict[format_str][year] = []
format_to_year_to_value_dict[format_str][year].append(value)
Czy istnieje coś takiego jak defaultdict dla list w wewnętrznej sprawie dict? – WilliamKF
Właśnie to edytowałem. Potrzebujesz tylko funkcji, która zwraca 'defaultdict (list)', a nie tylko '{}' dla brakujących kluczy. –