Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从Python中的普通字典创建嵌套字典_Python_Dictionary_Nested - Fatal编程技术网

如何从Python中的普通字典创建嵌套字典

如何从Python中的普通字典创建嵌套字典,python,dictionary,nested,Python,Dictionary,Nested,我有如下输入json字典列表: data1 = { { "nm": "Oliver Cromwell", "cty": "United Kingdom", "hse": "Commonwealth", "yrs": "1653-1658" }, { "nm": "Richard Cromwell", "cty": "United Kingdom", "hse": "Commonwealth", "yrs": "1658

我有如下输入json字典列表:

data1 = 
{
  {
    "nm": "Oliver Cromwell",
    "cty": "United Kingdom",
    "hse": "Commonwealth",
    "yrs": "1653-1658"
  },
  {
    "nm": "Richard Cromwell",
    "cty": "United Kingdom",
    "hse": "Commonwealth",
    "yrs": "1658-1659"
  },
  {
    "nm": "Charles II",
    "cty": "United Kingdom",
    "hse": "House of Stuart",
    "yrs": "1660-1685"
  },...
 dic={"United Kingdom”:   {
  "House of Blois” : [“Stephen”],
  'yrs': '1135-1154'}
我想创建一个嵌套字典,如下所示:

data1 = 
{
  {
    "nm": "Oliver Cromwell",
    "cty": "United Kingdom",
    "hse": "Commonwealth",
    "yrs": "1653-1658"
  },
  {
    "nm": "Richard Cromwell",
    "cty": "United Kingdom",
    "hse": "Commonwealth",
    "yrs": "1658-1659"
  },
  {
    "nm": "Charles II",
    "cty": "United Kingdom",
    "hse": "House of Stuart",
    "yrs": "1660-1685"
  },...
 dic={"United Kingdom”:   {
  "House of Blois” : [“Stephen”],
  'yrs': '1135-1154'}
我遵循了这个逻辑,但它有一个功能缺陷:

dic={}
i=0
while i<len(data):
    for k,v in data[i].items():
        if data[i]['cty'] not in dic:
            dic[data[i]["cty"]]={}
        if data[i]['hse'] not in dic[data[i]['cty']]:
            dic[data[i]['cty']][data[i]['hse']] = []
            dic[data[i]['cty']][data[i]['hse']].append(data[i]['nm'])
            dic['yrs']=data[i]['yrs']
i+=1

您误解了目录迭代的工作原理。您试图一次完整地获取整个词典,但语言语义只提供
键、值对

for data1['cty'], data1['hse'], data1['nm'] , data1['yrs'] in data1:
这是错误的。迭代的方式更像这样:

for key, val in data1:
这四个项目按一定顺序排列,例如:

'cty', 'United Kingdom'
'hse', 'House of Blois'
'nm',  'Stephen'
'yrs', '1135-1154'
在四次连续迭代中

按照您的表达方式,您的四个条目是完全独立的:您不能依赖于顺序(使用公共dict)


为了帮助您获得完整的解决方案,您必须向我们展示两到三条记录,这样我们才能了解如何遍历它们。

您误解了目录迭代的工作原理。您试图一次完整地获取整个词典,但语言语义只提供
键、值对

for data1['cty'], data1['hse'], data1['nm'] , data1['yrs'] in data1:
这是错误的。迭代的方式更像这样:

for key, val in data1:
这四个项目按一定顺序排列,例如:

'cty', 'United Kingdom'
'hse', 'House of Blois'
'nm',  'Stephen'
'yrs', '1135-1154'
在四次连续迭代中

按照您的表达方式,您的四个条目是完全独立的:您不能依赖于顺序(使用公共dict)


为了帮助您获得完整的解决方案,您必须向我们展示两到三条记录,以便我们了解如何遍历它们。

要为每个国家创建一个新的房屋分组词典,您可以使用递归解决方案和
itertools。groupby

import itertools
data1=[{"nm": "Oliver Cromwell", "cty": "United Kingdom", "hse":"Commonwealth","yrs": "1653-1658"},{"nm": "Richard Cromwell", "cty": "United Kingdom", "hse": "Commonwealth","yrs": "1658-1659"}, {"nm": "Charles II", "cty": "United Kingdom", "hse": "House of Stuart","yrs": "1660-1685"}]
def group(data, path):
  current = next(path, None)
  return data if not current else {a:group([{c:d for c, d in i.items() if c != current} for i in b], path) for a, b in itertools.groupby(sorted(data, key=lambda x:x[current]), key=lambda x:x[current])}

print(group(data1, iter(['cty', 'hse'])))
输出:

{'United Kingdom': {'Commonwealth': [{'nm': 'Oliver Cromwell', 'yrs': '1653-1658'}, {'nm': 'Richard Cromwell', 'yrs': '1658-1659'}], 'House of Stuart': [{'nm': 'Charles II', 'yrs': '1660-1685'}]}}

要为每个国家创建一个新的房屋分组词典,您可以使用递归解决方案与
itertools.groupby

import itertools
data1=[{"nm": "Oliver Cromwell", "cty": "United Kingdom", "hse":"Commonwealth","yrs": "1653-1658"},{"nm": "Richard Cromwell", "cty": "United Kingdom", "hse": "Commonwealth","yrs": "1658-1659"}, {"nm": "Charles II", "cty": "United Kingdom", "hse": "House of Stuart","yrs": "1660-1685"}]
def group(data, path):
  current = next(path, None)
  return data if not current else {a:group([{c:d for c, d in i.items() if c != current} for i in b], path) for a, b in itertools.groupby(sorted(data, key=lambda x:x[current]), key=lambda x:x[current])}

print(group(data1, iter(['cty', 'hse'])))
输出:

{'United Kingdom': {'Commonwealth': [{'nm': 'Oliver Cromwell', 'yrs': '1653-1658'}, {'nm': 'Richard Cromwell', 'yrs': '1658-1659'}], 'House of Stuart': [{'nm': 'Charles II', 'yrs': '1660-1685'}]}}


您的第二个示例的语法无效。
data1
字典的其他可能项是什么?更多的例子会有所帮助。你有字典列表吗?所有的数据项都像:{'cty':'United Kingdom','hse':'House of Blois','nm':'Stephen','yrs':'1135-1154'}再说一次,它是字典列表吗?如果是,请在问题中添加完整的示例。请向我们展示您提供的示例数据的预期结果-
data1
。您的第二个示例的语法无效。
data1
字典中的其他可能项是什么?更多的例子会有所帮助。你有字典列表吗?所有的数据项都像:{'cty':'United Kingdom','hse':'House of Blois','nm':'Stephen','yrs':'1135-1154'}再说一次,它是字典列表吗?如果是这样,请在问题中添加完整的示例。请向我们展示您提供的示例数据的预期结果-
data1
。是的,您是对的,让我试试。对于data1.items()中的k,v,对吗?是的,但我仍然不认为这是您想要的。请扩展您发布的示例,在您的输入目录中至少包含两个国家。是的,您是对的,让我试试。对于data1.items()中的k,v,对吗?是的,但我仍然不认为这是您想要的。请扩展您发布的示例,在您的输入目录中至少包含两个国家。是的,就是这样。你的答案很完美。请你把它扩展一下,或者解释一下函数中发生了什么。谢谢。@user8910400很高兴能帮上忙!如果这个答案帮助你,请考虑接受它。非常感谢。是的,我接受你的回答。请你把它扩展一下,或者解释一下函数中发生了什么。谢谢。是的,就是这样。你的答案很完美。请你把它扩展一下,或者解释一下函数中发生了什么。谢谢。@user8910400很高兴能帮上忙!如果这个答案帮助你,请考虑接受它。非常感谢。是的,我接受你的回答。请你把它扩展一下,或者解释一下函数中发生了什么。非常感谢。