简体   繁体   中英

Dictionary of dictionaries from list of lists with year keys

I have a list of list like this:

[['2014', 'MALE', 'WHITE NON HISPANIC', 'Zachary', '90', '39'], 
['2014', 'MALE', 'WHITE NON HISPANIC', 'Zev', '49', '65']]

I want to converted in a dictionary like this:

{{2012: {1: 'David',
  2: 'Joseph',
  3: 'Michael',
  4: 'Moshe'},
2013: {1: 'David',
  2: 'Joseph',
  3: 'Michael',
  4: 'Moshe'},

I'm trying to do a list comprehension like this:

boy_names = {row[0]:{i:row[3]} for i,row in enumerate(records) if row[1]=='MALE'}

But the result I'm getting is like:

{'2011': {7851: 'Zev'}, '2012': {9855: 'Zev'}, 
'2013': {11886: 'Zev'}, '2014': {13961: 'Zev'}}

If I'm right, I think I'm taking the last value and its row number from enumerate by the year key, but no idea how to solve it.

I believe you need

data = [['2014', 'MALE', 'WHITE NON HISPANIC', 'Zachary', '90', '39'], 
['2014', 'MALE', 'WHITE NON HISPANIC', 'Zev', '49', '65']]

result = {}
for i in data:           #Iterate sub-list
    result.setdefault(i[0], []).append(i[3])   #Form DICT
    
result = {k: dict(enumerate(v, 1)) for k, v in result.items()}   #Use enumerate to get index number
print(result)
# {'2014': {1: 'Zachary', 2: 'Zev'}}

You can use the length of the sub-dict under the year key to calculate the next incremental numeric key for the sub-dict under the current year. Use the dict.setdefault method to default the value of a new key to an empty dict:

boy_names = {}
for year, _, _, name, _, _ in records:
    record = boy_names.setdefault(int(year), {})
    record[len(record) + 1] = name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM