1

我尝试从文件创建一个多字典;

k = []
with open('directory file txt',r) as f:
    for line in f:
        k.append(line.strip().split('.'))

如何创建这样的多字典:

dict=[key1][key2][key3][key4]='value'

其中key1是第一行的第一个元素,key2第二个等。

4

1 回答 1

6

反转列表并嵌套结果:

result = {}
with open('directory file txt',r) as f:
    for line in f:
        keys = line.strip().split('.')
        value = keys[-1]
        for key in reversed(keys[1:-1]):
            value = {key: value}
        result[keys[0]] = value

这并不能很好地处理“更高”重复的键;如果您有重复的密钥,则需要使用稍微麻烦的设置(defaultdict()我认为不会更好地处理这种情况):

result = {}
with open('directory file txt',r) as f:
    for line in f:
        keys = line.strip().split('.')
        current = result
        for key in keys[:-2]:
            current = current.setdefault(key, {})
        current[keys[-2]] = keys[-1]
于 2012-11-30T15:20:36.070 回答