di中的Python翻译列表/dicts

2024-10-01 05:02:17 发布

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

Sorry, I didn't really know what to put in title, I hope the example will be enough

案例1-列表

我有一个这样的对象:

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

我想要一个像这样的物体:

^{pr2}$

案例2-dict

另一个我能收到的东西是这样的:

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

我想得到:

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

我的问题是,有没有lib能做到这一点?如果没有,最有效/优化的方法是什么?在

You can consider that in the first case the list I received will be always complete, that means that no number will be skipped


Tags: thekeyinthatvaluebewill案例
2条回答

从这里开始:

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',
})

输出:

^{pr2}$

对于第一个案子

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

[拆分旧字典键之一以获得真正的键。然后用这个键构造新的dict。我觉得这是一种不好的做法,但它很管用。所以你可以看看。在

相关问题 更多 >