How do I get a key and its value from a dictionary?

Question:

I have a dictionary, and I want to get a key & value SEPERATED out of it:

values = {
    "a": 123,
    "b": 173,
    "c": 152,
    "d": 200,
    "e": 714,
    "f": 71
}

Is there a way to do something like this:

dictValue = values[2] #I know this will be an error
dictKey = "c"
dictValue = 152

Thanks!

Asked By: Tousend1000

||

Answers:

Create an auxiliary dictionary with integer keys:

d = dict(enumerate(values.items()))
dictKey, dictValue = d[2]
#('c', 152)
Answered By: cards

Build a new dict:

values = {
    "a": 123,
    "b": 173,
    "c": 152,
    "d": 200,
    "e": 714,
    "f": 71
}

def get_the_idx_to_value_thingy(some_map):
    return {i: v for i, v in enumerate(some_map.values())}
    # or, if you trying to be clever:
    #   return list(some_map.values())

idx_to_value = get_the_idx_to_value_thingy(values)
print(idx_to_value[2])  # > = 152

You’ll have to call helper function get_the_idx_to_value_thingy each time you add/delete a key or update an entry.

# Oops!
del values['e']; del values['b']
new_idx_map_thingy = get_the_idx_to_value_thingy(values)
# LET's do this!
values['fToTheMAX!'] = values.pop('f')
new_idx_map_thingy = get_the_idx_to_value_thingy(values)
Answered By: rv.kvetch
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.