-2

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!

  • use `values.items()` – Hanna Mar 23 '23 at 20:11
  • 1
    By what reasoning should `values[2]` yield a key of c and a value of 152? – Scott Hunter Mar 23 '23 at 20:12
  • It's not really clear what you are trying to do. You know `values[2]` is an error, but what is it suppose to represent? Do you basically want some function like `key, value = magic(values, 2)` so that `key == "c"` and `value == 152`, under the assumption that the keys are ordered? – chepner Mar 23 '23 at 20:24

2 Answers2

0

Create an auxiliary dictionary with integer keys:

d = dict(enumerate(values.items()))
dictKey, dictValue = d[2]
#('c', 152)
cards
  • 3,936
  • 1
  • 7
  • 25
0

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)
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53