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!
Answers:
Create an auxiliary dictionary with integer keys:
d = dict(enumerate(values.items()))
dictKey, dictValue = d[2]
#('c', 152)
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)
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!
Create an auxiliary dictionary with integer keys:
d = dict(enumerate(values.items()))
dictKey, dictValue = d[2]
#('c', 152)
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)