Home > database >  Appending a list in a dictionary
Appending a list in a dictionary

Time:01-18

I have list of a list of dictionaries on hurricane data called list_hurricane, which looks like

**Simplified View**
  Hurricane A                    Hurricane B
[[{key1:value1, key2:value2,...}],[{key1:value1, key2:value2,...}]]


**Full View**:
[[{'name': 'Cuba I', 'month': 'October', 'year': 1924, 'max_sustained_wind': 165, 'area_affected': ['Central America', 'Mexico', 'Cuba', 'Florida', 'The Bahamas'], 'damage': 'Damages not recorded', 'death': 90}], [{'name': 'San Felipe II Okeechobee', 'month': 'September', 'year': 1928, 'max_sustained_wind': 160, 'area_affected': ['Lesser Antilles', 'The Bahamas', 'United States East Coast', 'Atlantic Canada'], 'damage': '100M', 'death': 4000}], [{'name': 'Bahamas', 'month': 'September', 'year': 1932, 'max_sustained_wind': 160, 'area_affected': ['The Bahamas', 'Northeastern United States'], 'damage': 'Damages not recorded', 'death': 16}], [{'name': 'Cuba II', 'month': 'November', 'year': 1932, 'max_sustained_wind': 175, 'area_affected': ['Lesser Antilles', 'Jamaica', 'Cayman Islands', 'Cuba', 'The Bahamas', 'Bermuda'], 'damage': '40M', 'death': 3103}], etc...

I am trying to use the year as a key and return each dictionary as the value. The problem is some years have multiple hurricanes/dictionaries.

I tried appending and thought I fixed it but now it is just showing None for those years with duplicates.

Here is what I have that returns None:

years[i] = [1924, 1928, 1932, 1932, 1933....]

dic_years = {}
for i in range(len(list_hurricane)):
    if years[i] in dic_years:
        dic_years[years[i]] = list_hurricane[i-1].append(list_hurricane[i])
    else:
        dic_years[years[i]] = list_hurricane[i]

Does anyone know how I could combine the lists, so that the key returns all the hurricanes for that year?

CodePudding user response:

defaultdict can be helpful here: https://docs.python.org/3/library/collections.html#collections.defaultdict

import collections
by_year = collections.defaultdict(list)
for hurricane in list_hurricane:
    year = hurricane['year']
    by_year[year].append(hurricane)

CodePudding user response:

I would have commented or asked for clarification as your code is not understandable but this line will always return None

list_hurricane[i-1].append(list_hurricane[i])

Either check if

dic_years[years[i]].append(list_hurricane[i])

fixes your issue or you need a different implementation.

CodePudding user response:

Using the list years is not needed. You can just go through the original list of hurricanes and append them to the dic_years dictionary.

dic_years = {}
for hurricane in list_hurricane:
    for key in hurricane:
        if key["year"] in dic_years:
            dic_years[key["year"]].append(key)
        else:
            dic_years[key["year"]] = [key]
  • Related