【问题标题】:nested dictionary how to create key and value as nested dictionary value as value .please help me嵌套字典如何创建键和值作为嵌套字典值作为值。请帮助我
【发布时间】:2021-10-25 17:12:50
【问题描述】:
check = {'Test_Category': {0: 'right', 1: 'wrong'}, 'arg1': {0: 'test2', 1: 'test12'},
         'arg2': {0: 'test4', 1: 'test41'}, 'arg3': {0: 'test5', 1: 'test55'},
         'arg4': {0: 'test6', 1: 'test67'}}

我想要预期的结果:

[{'Test_category': 'right', 'arg1': 'test2', 'arg2': 'test4', 'arg3': 'test5','arg4':'test6'}, 
{'Test_category': 'wrong', 'arg1': 'test12', 'arg2': 'test41', 'arg3': 'test55','arg4':'test67'}]

【问题讨论】:

  • 你甚至没有花时间正确地写出你的预期结果。
  • 任何人都有任何想法
  • 你试过什么?什么不起作用?

标签: python python-3.x list dictionary


【解决方案1】:

在这里,让我们尝试迭代check。我们将取两个空字典 d1 和 d2 ,我们可以在其中添加值。 d1 表示“0”的值,d2 表示“1”的值。在迭代时,我们将迭代本身是 dict 的值并相应地添加它。你的代码:

check = {'Test_Category': {0: 'right', 1: 'wrong'}, 'arg1': {0: 'test2', 1: 'test12'},
     'arg2': {0: 'test4', 1: 'test41'}, 'arg3': {0: 'test5', 1: 'test55'},
     'arg4': {0: 'test6', 1: 'test67'}}
d1={}
d2={}
for i in check:                #values of check[i] is itself a dict, we need value of 0 key and 1 key of inner dict
    d1[i]=check[i][0]       #values of 0 of inner dict and adding it to d1
for i in check:
    d2[i]=check[i][1]       #values of 1 of inner dict and adding it to d2

l=[d1,d2]         #list of d1 and d2
print(l)        #printing l

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多