I am trying to return a dictionary with key/value pairs, but this is what I got and it does not work.
def lists_to_dict(keys, value):
for i in values:
value[i]=map(int, value[i])
return keys
I am trying to return a dictionary with key/value pairs, but this is what I got and it does not work.
def lists_to_dict(keys, value):
for i in values:
value[i]=map(int, value[i])
return keys
Try this (best option):
return dict(zip(keys, value))
or this (a bit overly verbose):
return {key: v for key, v in zip(keys, value)}
or this (to show that one just arrived to Python from C++):
return {keys[i]: value[i] for i in range(len(keys))}
For {key: ...}
construction you can google dict comprehensions.
For zip
you can google zip.
These are important things so they might be worth reading, hence the links.
If you are trying to convert a two list into a dict, try using the zip command.
my version
def list_to_dict(keys, value):
return dict(zip(keys, value))
list_to_dict(['A', 'B', 'C'], [10, 20, 30])
Result
{'A': 1, 'B': 2, 'C': 3}
You make a for loop for "valueS", yet you give the function "value" First you should initialise the dictionary, try:
def lists_to_dict(keys, values):
out_dictionary = {}
for idx, key in enumerate(keys): ## idx will be an integer as index of keys
out_dictionary[key] = values[idx] ## assumes values and keys is equal length
return out_dictionary