简体   繁体   English

Python翻译字典中的列表/字典

[英]Python translate list/dicts in dict

Sorry, I didn't really know what to put in title, I hope the example will be enough 抱歉,我真的不知道该在标题中加上什么,我希望示例足以

Case 1 - list 情况1-清单

I have an object this format: 我有一个这种格式的对象:

{
    'key[0]': 'value 0',
    'key[1]': 'value 1',
    'key[2]': 'value 2'
}

And I want to get an object like this: 我想要一个这样的对象:

{
    'key': [
        'value 0',
        'value 1',
        'value 2'
    ]
}

Case 2 - dict 案例2-dict

Another object I could receive is something like this: 我可以收到的另一个对象是这样的:

{
    'key[subkey0]': 'value 0',
    'key[subkey1]': 'value 1',
    'key[subkey2]': 'value 2'
}

And I want to get: 我想得到:

{
    'key': {
        'subkey0': 'value 0',
        'subkey1': 'value 1',
        'subkey2': 'value 2'
    }
}

My question is, is there any lib that does that? 我的问题是,有没有这样做的库? If not, what is the most effective/optimized way to do that? 如果不是,最有效/最优化的方法是什么?

You can consider that in the first case the list I received will be always complete, that means that no number will be skipped 您可以考虑,在第一种情况下,我收到的列表将始终是完整的,这意味着不会跳过任何数字

Here's a start: 这是一个开始:

from collections import defaultdict
import re
import pprint

def convert(d):
    result = defaultdict(dict)
    for key, value in d.items():
        main, sub = re.match(r'(\w+)\[(\w+)\]', key).groups()
        result[main][sub] = value

    result = dict(result)  # just for display really
    pprint.pprint(result)

convert({
    'key1[subkey0]': 'value 0',
    'key1[subkey1]': 'value 1',
    'key2[subkey0]': 'value 2',
    'key2[subkey1]': 'value 3',
})

Output: 输出:

{'key1': {'subkey0': 'value 0', 'subkey1': 'value 1'},
 'key2': {'subkey0': 'value 2', 'subkey1': 'value 3'}}

For the first case, 对于第一种情况

old = {
    'key[0]': 'value 0',
    'key[1]': 'value 1',
    'key[2]': 'value 2'
}
new = dict()
the_key = old.keys()[0].split("[")[0]
new[the_key] = list()
for key in old:
    new[the_key].append(old[key])

print new

Splitted one of the old dictionary keys by [ to get the real key. 将旧字典键之一拆分为[以获取真实键。 Then constructed the new dict using this key. 然后使用此键构造新字典。 It strikes me as a bad practice, yet it works. 这对我来说是一种不好的作法,但是行得通。 So you can take a look. 所以你可以看看。

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

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