Given nested list: [1, (1, 2), [3, 4], {5: 6}]
, write a program that will make the element of these element as a key and position of these elements as a value.
My code: (read comments)
#!/usr/bin/python
def code(lst):
'''
lst: A nested hybrid list!
type: list
returns: linear dict
'''
d = {}
try:
for i, l in enumerate(lst):
if isinstance(l, list): # I know lists are unhashable
for e in l:
d[e] = i
elif isinstance(l, dict): # I know dicts are unhashable
for e in l.items():
d[e[0]] = i
d[e[1]] = i
else:
d[l] = i
except TypeError, e:
print "invalid key!"
print "Check your nested values"
except Exception, e: # One should catch every possible exception else code fault
printf "My Code fault!"
return d
And it is working!
Call:
print code([1, (1, 2), {3: 4}, [5, 6]])
output:
{(1, 2): 1, 1: 0, 3: 2, 4: 2, 5: 3, 6: 3}
I am Python learner, I written this code with assumption that key fetched from list will be unique e.g. [1, 2, [1, 2]]
is an invalid input.
[Question]
- I just want to know: How can I improve my code further, so it become small in length and fast?
I learn from "Apress Beginning Python" that one should avoid use of
isinstance()
. So is there any other way to write this code?Can you suggest me how to improve code for arbitrary nested and hybrid e.g.
# 0 1 2 3 <-- index [1, (1, 2), {3: [4, 5]}, [{6: 7} , 8]]
output:
{1: 0, (1, 2): 1, 3: 2, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3} # ^ ^ ^ ^ ^ ^ ^ ^ # index in outer list
I can handle nested at two level but nested at any level is not possible for me, please suggest a trick. A suggestion would be enough but should be Pythonic.
(3rd question is main problem for which I posted this question)
Edit:
As pointed @tcaswell:
How would you want to deal with
[1, {1: 2}]
?1
should be mapped to both0
and1
under your current rules.
For simplicity I am assuming this input is invalid. "assumption that key fetched from list will be unique"