characters = [num for num in range(20, 41)]
mapper = list(map(chr, characters))
print (mapper) # returning the list of all the ASCII characters w.r.t its value.
mapper = dict(map(chr, characters))
print(mapper)
In the above code, when I print 'mapper' converted to list object. I am getting the correct output. But when the same is converted to dictionary object. I am getting an error...
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
mapper = dict(map(chr, characters))
ValueError: dictionary update sequence element #0 has length 1; 2 is required
So, does that mean that map function can only covert into object type- tuple or list and NOT dictionary?
The result I am expecting is where ASCII value to be the dictionary 'keys' and the respective ASCII character as dictionary 'values' something like this:
{20: "\x14", 21: "\x15", 22: "\x16", ............ , 39: " ' ", 40: " ( "}
It seems like you really want to use map
, you can, but as @e4c5 stated: "that would be inelegant, more lines of code, unpythonic and slower", which is entirely true. But I'll provide an example using map
for you, since that's what you seemed to want:
The reason your code doesn't work is because a dictionary needs a key and a value, right now, you only the value
, no keys
. You can use zip
to zip the key from characters
to the value from map
:
characters = [num for num in range(20, 41)]
mapper = dict(zip(characters,map(chr, characters)))
print(mapper)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments