包含lis的词典

2024-06-16 11:22:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,它返回下面的字典

abc= {"type":"insecure","id":"1",
       "name":"peter","s_count":"2",
      "b_count":"1", "s_1_name":"melisa",
        "s_1_id":"2","s_2_name":"graham",
      "s_2_id":"4", "b_1_name":"henrik", 
        "b_1_id": "9"}

我想按以下方式修改词典:

^{pr2}$

逻辑如下:如果dictionary中有s_count,则创建一个包含所有以s开头的值的列表。例如,在我的示例中,创建一个包含不同字典的列表,每个字典都包含s_name和s_id,例如,在我的例子中,结果列表中有两个字典:

^{3}$

如果b计数值存在,对b也做同样的处理。在

有人能帮我吗?在


Tags: 函数nameid列表字典typecount方式
2条回答

我把它改进了一点,这样它就更灵活了。在

def extract_keys(mapping, prefix):
prefix = "{}_".format(prefix)

# test for the `.._count` key first, if it's not there, bail out early
if prefix + "count" not in mapping:
    return None

# find all matching keys, split out the counter for sorting and grouping
keys = [(k, int(k.split("_", -1)[-2])) for k in mapping if k.startswith(prefix) and k != prefix + "count"]
keys.sort(key=itemgetter(1))

# group keys on the counter, then generate a dictionary per counter value
return [{k[0].split("_", -1)[-1]: mapping[k[0]] for k in group} for c, group in groupby(keys, itemgetter(1))]

考虑下面的字典。在

^{pr2}$

使用该函数可以创建新词典或就地转换现有词典:

xyz = {k: v for k, v in abc.iteritems() if not k.startswith('s_a') and not k.startswith('b_')}
s_values = extract_keys(abc, 's_a')
if s_values is not None:
    xyz['s_a'] = s_values
b_values = extract_keys(abc, 'b')
if b_values is not None:
    xyz['b'] = b_values

转化后的输出为:

print xyz

{'b': [{'id': '9', 'name': 'henrik'}],
'id': '1',
'name': 'peter',
's_a': [{'id': '2', 'name': 'melisa'}, {'id': '4', 'name': 'graham'}],
'type': 'insecure'}

我会使用一个helper函数:

from itertools import groupby
from operator import itemgetter

def extract_keys(mapping, prefix):
    prefix = '{}_'.format(prefix)

    # test for the `.._count` key first, if it's not there, bail out early
    if prefix + 'count' not in mapping:
        return None

    # find all matching keys, split out the counter for sorting and grouping
    keys = [(k, int(k.split('_', 2)[1]))
        for k in mapping if k.startswith(prefix) and k != prefix + 'count']
    keys.sort(key=itemgetter(1))

    # group keys on the counter, then generate a dictionary per counter value
    return [{k[0].split('_', 2)[-1]: mapping[k[0]] for k in group}
        for c, group in groupby(keys, itemgetter(1))]

此函数按前缀提取密钥:

^{pr2}$

使用该函数可以创建新词典或就地转换现有词典:

xyz = {k: v for k, v in abc.iteritems() if not k.startswith('s_') and not k.startswith('b_')}
s_values = extract_keys(abc, 's')
if s_values is not None:
    xyz['s'] = s_values
b_values = extract_keys(abc, 'b')
if b_values is not None:
    xyz['b'] = b_values

这会将abc示例输入转换为:

>>> pprint(xyz)
{'b': [{'id': '9', 'name': 'henrik'}],
 'id': '1',
 'name': 'peter',
 's': [{'id': '2', 'name': 'melisa'}, {'id': '4', 'name': 'graham'}],
 'type': 'insecure'}

相关问题 更多 >