-1

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
  • 1
    Welcome to stack overflow! Your question is unclear. What is your input to the function, what is the current output, and what is the expected output? Please [edit] this to make a [mcve] – G. Anderson Oct 29 '20 at 18:11
  • 1
    Are you just trying to do `dict(zip(keys, values))`? – ShadowRanger Oct 29 '20 at 18:15

3 Answers3

2

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.

Kroshka Kartoshka
  • 1,035
  • 5
  • 23
  • To be clear, #3 is extremely non-idiomatic (and slower, and more prone to errors with mismatched input sizes). Basically any case of `for i in range(len(someseq)):` which does `someseq[i]` is a problem; indexing another sequence with it makes it worse. #2 is more customizable, but not necessary unless you're filtering or mutating the keys or values. – ShadowRanger Oct 29 '20 at 18:17
  • Yes, added this characteristic to the answer, thanks – Kroshka Kartoshka Oct 29 '20 at 18:18
0

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}
Fjord
  • 31
  • 3
0

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
max coenen
  • 11
  • 1