简体   繁体   English

从列表中提取值并使用 python 创建嵌套字典

[英]Extract values from a list and create nested dictionary using python

I am trying to extract values from a list and populate it in a nested dictionary.我正在尝试从列表中提取值并将其填充到嵌套字典中。

Input:输入:

['abc-bcd_10_01_physics_90_70_20',
 'abc-bcd_10_01_chemistry_85_75_10',
 'ac-bd_10_03_biology_60_50_10',
 'ad-bcd_10_05_physics_70_50_20',
 'ac-bd_10_03_physics_65_50_15']

Expected Output:预期 Output:

[
  {'first-name' : 'abc',
    'last-name' : 'bcd',
    'class' : '10',
    'roll-number' : 1,
    'marks' : [{'subject':'physics',
              'total' : 90,
              'theory' : 70,
              'practical' : 20},
              {'subject':'chemistry',
              'total' : 85,
              'theory' : 75,
              'practical' : 10}]
  },
  {'first-name' : 'ac',
    'last-name' : 'bd',
    'class' : '10',
    'roll-number' : 3,
    'marks' : [{'subject':'biology',
              'total' : 60,
              'theory' : 50,
              'practical' : 10},
              {'subject':'physics',
              'total' : 65,
              'theory' : 50,
              'practical' : 15},
              ]
  },
  {'first-name' : 'ad',
    'last-name' : 'bcd',
    'class' : '10',
    'roll-number' : 5,
    'marks' : [{'subject':'physics',
              'total' : 70,
              'theory' : 50,
              'practical' : 20}]
  }
]

I am able to extract values from the input list using split function and populate it in a plain dictionary, but stuck at the point where I need to group by the keys first-name,last-name,class,roll-number and collect the list of other keys under a common key called marks .我可以使用拆分 function 从输入列表中提取值并将其填充到普通字典中,但停留在我需要按名字、姓氏、class、roll-number键分组并收集一个称为标记的通用键下的其他键的列表。

Also, I need the keys inside the dictionaries to be in the same order as specified above.另外,我需要字典中的键与上面指定的顺序相同。

To group the subject scores by name, class and roll number, you need to build a dictionary with those values as the key (I've made one by joining them with # , a string I assume cannot occur in class or roll number ), and then push each subject into an array of marks.要按名称、class 和卷号对主题分数进行分组,您需要以这些值作为键来构建一个字典(我已经通过将它们与#连接起来制作了一个字典,我认为该字符串不会出现在classroll number中),然后将每个主题推入一系列标记中。 Once you have iterated over all the input, use dict.values to convert to a list of dictionaries:遍历所有输入后,使用dict.values转换为字典列表:

from collections import defaultdict

marks = ['abc-bcd_10_01_physics_90_70_20',
 'abc-bcd_10_01_chemistry_85_75_10',
 'ac-bd_10_03_biology_60_50_10',
 'ad-bcd_10_05_physics_70_50_20',
 'ac-bd_10_03_physics_65_50_15']

results = defaultdict(dict)

for m in marks:
    name, classn, roll, subject, total, theory, practical = m.split('_')
    fn, ln = name.split('-')
    key = '#'.join([name, classn, roll])
    if key not in results:
        results[key] = { 'first_name' : fn,
                         'last_name' : ln,
                         'class' : classn,
                         'roll' : int(roll),
                         'marks' : []
                        }
    results[key]['marks'].append({ 'subject' : subject,
                                   'total' : int(total),
                                   'theory' : int(theory),
                                   'practical' : int(practical)
                                  })
    
results = list(results.values())
print(results)

Output: Output:

[
 {'first_name': 'abc',
  'last_name': 'bcd',
  'class': '10',
  'roll': 1,
  'marks': [{'subject': 'physics', 'total': 90, 'theory': 70, 'practical': 20}, 
            {'subject': 'chemistry', 'total': 85, 'theory': 75, 'practical': 10}
           ]
 },
 {'first_name': 'ac',
  'last_name': 'bd',
  'class': '10',
  'roll': 3,
  'marks': [{'subject': 'biology', 'total': 60, 'theory': 50, 'practical': 10}, 
            {'subject': 'physics', 'total': 65, 'theory': 50, 'practical': 15}
           ]
 },
 {'first_name': 'ad',
  'last_name': 'bcd',
  'class': '10',
  'roll': 5,
  'marks': [{'subject': 'physics', 'total': 70, 'theory': 50, 'practical': 20}
           ]
 }
]

Simple.简单的。

Data:数据:

d = ['abc-bcd_10_01_physics_90_70_20',
 'abc-bcd_10_01_chemistry_85_75_10',
 'ac-bd_10_03_biology_60_50_10',
 'ad-bcd_10_05_physics_70_50_20',
 'ac-bd_10_03_physics_65_50_15']
L = []
for m in d:
    first_name, last_name = m.split("-")[:2]
    last_name = last_name.split("_")[0]
    class_, roll_number, subject = m.split("_")[1:4]
    total, theory, practical = m.split("_")[4:]
    L.append([first_name, last_name, class_, roll_number, subject, total, theory, practical])
L = sorted(L, key=lambda x:x[:2])

d = {}
processed = []
for i in L:
    f = dict(zip(['first_name', 'last_name', 'class', 'roll_number', 'subject', 'total', 'theory', 'practical'], i))
    if i[:2] in processed:
        d['-'.join(i[:2])].append(f)
    else:
        d['-'.join(i[:2])] = [f]
        processed.append(i[:2])
import pprint
pprint.pprint(d)
{'abc-bcd': [{'class': '10',
              'first_name': 'abc',
              'last_name': 'bcd',
              'practical': '20',
              'roll_number': '01',
              'subject': 'physics',
              'theory': '70',
              'total': '90'},
             {'class': '10',
              'first_name': 'abc',
              'last_name': 'bcd',
              'practical': '10',
              'roll_number': '01',
              'subject': 'chemistry',
              'theory': '75',
              'total': '85'}],
 'ac-bd': [{'class': '10',
            'first_name': 'ac',
            'last_name': 'bd',
            'practical': '10',
            'roll_number': '03',
            'subject': 'biology',
            'theory': '50',
            'total': '60'},
           {'class': '10',
            'first_name': 'ac',
            'last_name': 'bd',
            'practical': '15',
            'roll_number': '03',
            'subject': 'physics',
            'theory': '50',
            'total': '65'}],
 'ad-bcd': [{'class': '10',
             'first_name': 'ad',
             'last_name': 'bcd',
             'practical': '20',
             'roll_number': '05',
             'subject': 'physics',
             'theory': '50',
             'total': '70'}]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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