Python动态字典创建

时间:2014-02-28 07:48:06

标签: python

几天前我开始使用python。任何人都可以帮我实现以下目标吗?

我有两个清单 -

mylist1 = ["Country", "State", "City", "Name", "Age"]

另一个清单 -

mylist2 = [["India", "Maharashtra", "Mumbai", "Tom", 30],
           ["India", "Maharashtra", "Mumbai", "John", 40],
           ["India", "Maharashtra", "Pune", "Ronny", 25]
           ["India", "Madhya Pradesh", "Indore", "Jade", 35]]

用户将获得字典级别,例如

level = 4

所以应该创建深度为3的字典,如下所示 -

mydict = {"India":{"Maharashtra":{"Mumbai":{"Tom":{"Age":30},"John":{"Age":40}},
                                  "Pune"  :{"Ronny":{"Age":25}},
                   "Madhya Pradesh":{"Indore": {"Jade": {"Age" : 35}}}
               }

上面的字典可能会有一些拼写错误。我没有尝试任何方法让这个工作。

另请注意,上述列表可以更改如下 -

mylist1 = ["State", "City", "Name", "Age"]

另一个清单 -

mylist2 = [["Maharashtra", "Mumbai", "Tom", 30],
           ["Maharashtra", "Mumbai", "John", 40],
           ["Maharashtra", "Pune", "Ronny", 25]
           ["Madhya Pradesh", "Indore", "Jade", 35]]

因此,在上述情况下,用户可以提供等级= 3。

1 个答案:

答案 0 :(得分:0)

可以使用Autovivification完成此操作。这个answer提供了使用autovivification创建嵌套字典的代码。

根据您的情况调整代码,我们可以将输出转换为:

from pprint import pprint
class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value


a = AutoVivification()
for entry in mylist2:
    a[entry[0]][entry[1]][entry[2]][entry[3]][mylist1[-1]] = entry[4]
pprint(a)

此外,您可以根据entry参数更改level的索引。

希望这有帮助!