简体   繁体   中英

How to store a list as a dictionary - python

I know how to store in a list but how do I store these values as a dictionary instead?

    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

So far I have come to the conclusion that I could store items as items = {} but I don't know how to duplicate the .append method with a dictionary. Nor do I know how to access a dictionary like items[a][b] does. Any suggestions?

One major difference between a dictionary and a list is that dictionaries have "keys" while lists have "indices". So instead of .append() , you need to assign the value to a specific key, like this:

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

Take a look at the docs on dict , as well as some tutorials on beginner Python programming.

Declaring a dictionary:

dictionary = {}

Adding to a dictionary:

dictionary[newkey] = newvalue

Accessing a dictionary:

print (dictionary[newkey])

Returns:

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]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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