用简单列表填充嵌套字典

时间:2020-09-09 14:25:20

标签: python list dictionary

我有一个useEffect(),我想填充到字典中,但是我的字典目前是 [Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See url for tips about how to debug and fix this problem.]

必需的输出:list = [1,2,3,4,5]

2 个答案:

答案 0 :(得分:2)

.Interior.Color

输出:

my_list = [1,2,3,4,5]
my_dict = {'a': None,'b': [None, None, None],'c': None}
for key in my_dict.keys():
    if my_dict[key] == None:
        my_dict[key] = my_list[0]
        my_list.pop(0)
    else:
        if type(my_dict[key]) is list:
            for item in range(len(my_dict[key])):
                if my_dict[key][item] == None:
                    my_dict[key][item] = my_list[0]
                    my_list.pop(0)
print(my_dict)

答案 1 :(得分:0)

此代码段将第一个元素分配给a,将最后一个元素分配给c,所有中间元素都分配给b

lis = [1,2,3,4,5]
output = {'a': lis[0], 'b': lis[1:len(lis)-1], 'c': lis[len(lis)-1]}
print(output)

输出:

{'a': 1, 'b': [2, 3, 4], 'c': 5}