Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.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 - Fatal编程技术网

Python 在字典中建立字典

Python 在字典中建立字典,python,Python,我有一个需要转换的词典列表: my_dictionary = {} my_array = [{'first': 'this'}, {'second': 'this'}] 我想要的是键入my_dictionary,然后拥有与my_array中的项相等的子字典,如下所示: my_dictionary = {'red' : {'first': 'this', 'second' : 'this'}} 理论上,我所拥有的是: for i in my_array: my_dictionary['

我有一个需要转换的词典列表:

my_dictionary = {}
my_array = [{'first': 'this'}, {'second': 'this'}]
我想要的是键入
my_dictionary
,然后拥有与
my_array
中的项相等的子字典,如下所示:

my_dictionary = {'red' : {'first': 'this', 'second' : 'this'}}
理论上,我所拥有的是:

for i in my_array:
    my_dictionary['red'] = dict(i.items())
但我得到了一个错误:

TypeError:“dict”对象不可调用

我意识到,这可能是因为在第一次迭代之后,我没有创建字典,我只是在添加。是否有一种方法可以从
my_array
中的每个项目中提取密钥,以便更像以下那样指定它:

for i in my_array:
    my_dictionary['red'][key_from_item_in_my_array] = my_array[key_from_item_in_my_array]

但是我不知道怎么做。

似乎您想要将字典数组合并到一个字典中,然后将该字典放入另一个字典中。合并很容易:

new_dict = {}
for i in my_array:
    new_dict.update(i)
现在,您可以将合并的词典放入第二本词典:

my_dictionary = {}
my_dictionary["red"] = new_dict
这将产生:

my_dictionary = {'red': {'first': 'this', 'second': 'this'}}

似乎要将字典数组合并到单个字典中,然后将该字典放入另一个字典中。合并很容易:

new_dict = {}
for i in my_array:
    new_dict.update(i)
现在,您可以将合并的词典放入第二本词典:

my_dictionary = {}
my_dictionary["red"] = new_dict
这将产生:

my_dictionary = {'red': {'first': 'this', 'second': 'this'}}

我敢打赌你的代码中有一个名为
dict
的变量。数组是什么?这是我的数组吗?啊,是的,我真的重新做了这个。最好使用构造函数方法,我只得到最后一次迭代的数据。所以每次迭代都会覆盖它。如何将键值对添加到字典中?很抱歉,现在编辑,是的数组是我的数组。您的代码不会引发
TypeError
。我打赌您的代码中有一个名为
dict
的变量。数组是什么?这是我的数组吗?啊,是的,我真的重新做了这个。最好使用构造函数方法,我只得到最后一次迭代的数据。所以每次迭代都会覆盖它。如何将键值对添加到字典中?很抱歉,现在编辑,是的数组是我的数组。您的代码没有引发
类型错误