Home > Mobile >  Store the value of a key-value by its order?
Store the value of a key-value by its order?

Time:01-06

Reading about data structures and have a question. This is a dictionary:

example = {'the': 8,
 'metal': 8,
 'is': 23,
 'worth': 3,
 'many': 3,
 'dollars': 2,
 'right': 2}

How to store to a variable the value of a key/value pair by order?

For example, how to store the value of the third pair, which is 23?

Tried this, which is not correct:

for k in example:
    if k == 3:
        a_var = example(k)

CodePudding user response:

If you know the key/values have been inserted in the correct order, you can use islice() to get the third key/value pair. This has the benefit of not needing to create a whole list of values and is a bit simpler than explicitly writing a loop:

from itertools import islice

example = {
    'the': 8,
    'metal': 8,
    'is': 23,
    'worth': 3,
    'many': 3,
    'dollars': 2,
    'right': 2
}

key, val = next(islice(example.items(), 2, None))
# 'is', 23

If you only want the value instead of the key/value pair, then of course you can pass values() instead of items() to islice():

val = next(islice(example.values(), 2, None))
# 23

CodePudding user response:

This does what you need:

example = {'the': 8,
 'metal': 8,
 'is': 23,
 'worth': 3,
 'many': 3,
 'dollars': 2,
 'right': 2}
k=0
for key in example:
    k =1
    if k == 3:
        a_var = example[key]
print(a_var)

Output:

23

CodePudding user response:

If you really think you need this:

def find( example, ordinal):
    for k,value in enumerate(example.values()):
        if k == ordinal:
            return value

or

def find( example, ordinal):
    return list(example.values())[ordinal]

CodePudding user response:

a_var=example[list(example.keys())[3-1]]
  •  Tags:  
  • Related