将非结构化的名称和数据列表转换为嵌套字典

时间:2018-01-21 00:03:04

标签: python dictionary nested defaultdict

我有一个"非结构化"列表看起来像这样:

Officer=True

非结构化,因为该列表包含以下几组:

  • 姓名,官员身份,人口统计信息)三元组,或
  • 名称,人口统计信息)对。

在后一种情况下,Race / Gender / Age和前者NaN。人口统计信息字符串代表res = { 'Joe Schmoe': { 'race': 'W', 'gender': 'M', 'age': 64, 'officer': False }, 'Richard Johnson': { 'race': 'W', 'gender': 'M', 'age': 48, 'officer': True }, 'Adrian Stevens': { 'race': 'NaN', 'gender': 'NaN', 'age': 27, 'officer': False } } ,其中import re def fix_demographic(info): # W / M / ?? --> W / M / NaN # ?/M/? --> NaN / M / NaN # Keep as str NaN rather than np.nan for now race, gender, age = re.split('\s*/\s*', re.sub('\?+', 'NaN', info)) return race, gender, age 由文字问号代表。这是我想去的地方:

demographic = re.compile(r'(\w+|\?+)\s*\/\s*(\w+|\?+)\s*\/\s*(\w+|\?+)')


def parse_victim_info(info: list):
    res = defaultdict(dict)
    for i in info:
        if not demographic.fullmatch(i) and i.lower() != 'officer':
            # We have a name
            previous = 'name'
            name = i
        if i.lower() == 'officer':
            res[name]['officer'] = True
            previous = 'officer'
        if demographic.fullmatch(i):
            # We have demographic info; did "OFFICER" come before it?
            if previous == 'name':
                res[name]['officer'] = False
            race, gender, age = fix_demographic(i)
            res[name]['race'] = race
            res[name]['gender'] = gender
            res[name]['age'] = int(age) if age.isnumeric() else age
            previous = None
    return res

>>> parse_victim_info(info)
defaultdict(dict,
            {'Adrian Stevens': {'age': 27,
              'gender': 'NaN',
              'officer': False,
              'race': 'NaN'},
             'Richard Johnson': {'age': 48,
              'gender': 'M',
              'officer': True,
              # ... ...

现在我已经建立了两个功能来完成这项工作。第一个是在下面并处理人口统计信息字符串。 (我对这个很好;只是把它放在这里作为参考。)

this.todo

第二个函数解构列表并将其值抛出到字典结果中的不同位置:

List

这第二个功能感觉太冗长了。对于它正在做的事情是乏味的。

有没有更好的方法可以更巧妙地记住迭代中看到的最后一个值的分类?

2 个答案:

答案 0 :(得分:4)

这种事情很适合generator

代码:

def find_triplets(data):
    data = iter(data)
    while True:
        name = next(data)
        demo = next(data)
        officer = demo == 'OFFICER'
        if officer:
            demo = next(data)
        yield name, officer, demo

测试代码:

info = [
    'Joe Schmoe',
    'W / M / 64',
    'Lillian Schmoe',
    'W / F / 60',
    'Richard Johnson',
    'OFFICER',
    'W / M /48',
    'Adrian Stevens',
    '? / ? / 27'
]

for x in find_triplets(info):
    print(x)

结果:

('Joe Schmoe', False, 'W / M / 64')
('Lillian Schmoe', False, 'W / F / 60')
('Richard Johnson', True, 'W / M /48')
('Adrian Stevens', False, '? / ? / 27')

将元组三元组转换为dict

import re

def fix_demographic(info):
    # W / M / ?? --> W / M / NaN
    # ?/M/?  --> NaN / M / NaN
    # Keep as str NaN rather than np.nan for now
    race, gender, age = re.split('\s*/\s*', re.sub('\?+', 'NaN', info))
    return dict(race=race, gender=gender, age=age)


data_dict = {name: dict(officer=officer, **fix_demographic(demo))
             for name, officer, demo in find_triplets(info)}

print(data_dict)

结果:

{
    'Joe Schmoe': {'officer': False, 'race': 'W', 'gender': 'M', 'age': '64'}, 
    'Lillian Schmoe': {'officer': False, 'race': 'W', 'gender': 'F', 'age': '60'}, 
    'Richard Johnson': {'officer': True, 'race': 'W', 'gender': 'M', 'age': '48'}, 
    'Adrian Stevens': {'officer': False, 'race': 'NaN', 'gender': 'NaN', 'age': '27'}
}

答案 1 :(得分:0)

您可以在Python3中使用itertools.groupby

import itertools
import re
info = [
'Joe Schmoe',
'W / M / 64',
'Lillian Schmoe',
'W / F / 60',
'Richard Johnson',
'OFFICER',
'W / M /48',
'Adrian Stevens',
'? / ? / 27'
]
data = [list(b) for a, b in itertools.groupby(info, key=lambda x:x.count('/') > 0 or x == 'OFFICER')]

final_data = {data[i][0]:{**{a:'NaN' if b == '?' else (int(b) if b.isdigit() else b) for a, b in zip(['race', 'gender', 'age'], filter(None, re.split('\s+|/', [h for h in data[i+1] if h.count('/') > 0][0])))}, **{"officer":"OFFICER" in data[i+1]}} for i in range(0, len(data), 2)} 

输出:

{'Joe Schmoe': {'race': 'W', 'gender': 'M', 'age': 64, 'officer': False}, 'Lillian Schmoe': {'race': 'W', 'gender': 'F', 'age': 60, 'officer': False}, 'Richard Johnson': {'race': 'W', 'gender': 'M', 'age': 48, 'officer': True}, 'Adrian Stevens': {'race': 'NaN', 'gender': 'NaN', 'age': 27, 'officer': False}}