简体   繁体   English

从字典中检索列表

[英]Retrieving a list from a dictionary

I have the list mydicts = [] which contains 我有清单mydicts = [] ,其中包含

[{'Frank': {'Jack': 0, 'Kevin': 0, 'Sam': 0},
    'Sam': {'Frank': 0, 'Jack': 0, 'Kevin': 0},
    'Kevin': {'Frank': 0, 'Jack': 0, 'Sam': 0},
    'Jack': {'Frank': 0, 'Kevin': 0, 'Sam': 0} }]

I am however trying to get it in this format in order for me to perform some operations: 但是,我试图以这种格式获取它,以便执行一些操作:

d = {'Frank': {'Jack': 0, 'Kevin': 0, 'Sam': 0},
'Sam': {'Frank': 0, 'Jack': 0, 'Kevin': 0},
'Kevin': {'Frank': 0, 'Jack': 0, 'Sam': 0},
'Jack': {'Frank': 0, 'Kevin': 0, 'Sam': 0} }

I tried doing this 我尝试这样做

sm_list = list(mydicts)
d = sm_list

But it did not work. 但这没有用。 How can I fix it? 我该如何解决?

You can just access to it by using list indices: 您可以使用列表索引来访问它

my_dicts = [{'Frank': {'Jack': 0, 'Kevin': 0, 'Sam': 0},
    'Sam': {'Frank': 0, 'Jack': 0, 'Kevin': 0},
    'Kevin': {'Frank': 0, 'Jack': 0, 'Sam': 0},
    'Jack': {'Frank': 0, 'Kevin': 0, 'Sam': 0} }]

d = my_dicts[0]

Notes: 笔记:

  • The proper name for [...] is list , not array. 为正确的名称[...]列表 ,而不是数组。

  • By accessing to my_dicts[0] , you are accessing to the first element. 通过访问my_dicts[0] ,您正在访问第一个元素。 With my_dicts[1] you will access to the second element. 使用my_dicts[1]您将访问第二个元素。 And so on. 等等。

  • When you do list(mydicts) , it doesn't have effect because my_dicts is already a list. 当您执行list(mydicts) ,它无效,因为my_dicts已经是一个列表。

You can solve this issue simply by doing this: 您只需执行以下操作即可解决此问题:

d = mydicts[0]

This returns the first value from mydicts , which conveniently is exactly what you want. 这将从mydicts返回第一个值,该值恰好是您想要的。

What you want can be obtained by retrieving the first (and only) element in your array -- which is already what Python calls a list -- since it's exactly what you seek. 可以通过检索数组中的第一个(也是唯一的)元素来获得所需的内容(这已经是Python所谓的list ,因为这正是您要查找的内容。 The first element in a list/array is the one with an index of 0. 列表/数组中的第一个元素是索引为0的元素。

mydicts = [{'Frank': {'Jack': 0, 'Kevin': 0, 'Sam': 0},
            'Sam': {'Frank': 0, 'Jack': 0, 'Kevin': 0},
            'Kevin': {'Frank': 0, 'Jack': 0, 'Sam': 0},
            'Jack': {'Frank': 0, 'Kevin': 0, 'Sam': 0},}]

d = mydicts[0]

print "d's contents: {"
for k, v in d.iteritems():
    print '    {}: {},'.format(k, v)
print '}'

Output: 输出:

d's contents: {
    Frank: {'Sam': 0, 'Jack': 0, 'Kevin': 0},
    Sam: {'Frank': 0, 'Jack': 0, 'Kevin': 0},
    Kevin: {'Frank': 0, 'Jack': 0, 'Sam': 0},
    Jack: {'Frank': 0, 'Sam': 0, 'Kevin': 0},
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM