繁体   English   中英

如何将列表存储为字典-Python

[英]How to store a list as a dictionary - python

我知道如何存储在列表中,但是如何将这些值存储为字典?

    items = []
    for a in range(10):
        items.append([])
        for b in range(10):
            if function() == condition:
                items[a].append(WRONG)
    for a,b in oldItems:
        items[a][b] = RIGHT

到目前为止,我得出的结论是,我可以将项目存储为items = {}但我不知道如何用字典复制.append方法。 我也不知道如何像items[a][b]一样访问字典。 有什么建议么?

字典和列表之间的主要区别在于字典具有“键”,而列表具有“索引”。 因此,您需要将值分配给特定键,而不是.append() ,如下所示:

items = {}
for a in range(10):
    items[a] = []    # items[a] creates a key 'a' and stores an empty list there
    for b in range(10):
        if function() == condition:
            items[a].append(WRONG)
for a, b in oldItems:
    items[a][b] = RIGHT

看一看dict上的文档 ,以及有关Python初学者编程的一些教程。

声明字典:

dictionary = {}

添加到字典:

dictionary[newkey] = newvalue

访问字典:

print (dictionary[newkey])

返回值:

newvalue
 #take input from User
    N = int(raw_input())

 #declare a dictionary
    dictn = {}

    for _ in range(N):
            SplitInput = raw_input().split()
            keyValue, ListValues = SplitInput[0], SplitInput[1:]
            ListValues = map(float, ListValues)
            dictn[keyValue] = ListValues
    print dictn

    input:
    3
    FirstKey 11 12 13
    SecondKey 45 46 47
    ThirdKey 67 68 69

    Output:
    {'SecondKey': [45.0, 46.0, 47.0], 'ThirdKey': [67.0, 68.0, 69.0], 'FirstKey': [11.0, 12.0, 13.0]}

暂无
暂无

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

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