python - Convert hybrid nested list into linear dict -
given nested list: [1, (1, 2), [3, 4], {5: 6}]
, write program make element of these element key , position of these elements value.
my code: (read comments)
#!/usr/bin/python def code(lst): ''' lst: nested hybrid list! type: list returns: linear dict ''' d = {} try: i, l in enumerate(lst): if isinstance(l, list): # know lists unhashable e in l: d[e] = elif isinstance(l, dict): # know dicts unhashable e in l.items(): d[e[0]] = d[e[1]] = else: d[l] = except typeerror, e: print "invalid key!" print "check nested values" except exception, e: # 1 should catch every possible exception else code fault printf "my code fault!" return d
and 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 python learner, written code assumption key fetched list unique e.g. [1, 2, [1, 2]]
invalid input.
[question]
- i want know: how can improve code further, become small in length , fast?
i learn "apress beginning python" 1 should avoid use of
isinstance()
. there other way write code?can suggest me how improve code arbitrary nested , 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 @ 2 level nested @ level not possible me, please suggest trick. suggestion enough should pythonic.
(3rd question main problem posted question)
edit:
as pointed @tcaswell:
how want deal
[1, {1: 2}]
?1
should mapped both0
,1
under current rules.
for simplicity assuming input invalid. "assumption key fetched list unique"
biglist = [1, (1, 2), {(3,9): [4, 5]}, [{6: 7} , 8]] linear_dict = dict() def nestedlist(l, index = none, break_tuple = false): count, item in enumerate(l): if type(item) list: nestedlist(item, index if index else count) elif type(item) dict: nestedlist(item.iteritems(), index if index else count, true) elif type(item) tuple , break_tuple: nestedlist(list(item), index) else: linear_dict[item] = index if index else count nestedlist(biglist) print linear_dict {(1, 2): 1, 1: 0, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3, (3, 9): 2}
this more of problem on recursion rather lists, tuples , dictionaries per say.
about isinstance()
, type()
, read these:
- differences between isinstance() , type() in python
- what best (idiomatic) way check type of python variable?
although, things mentioned here not apply question, because msw mentioned, seems more textbook question. apart that, answers in link contain advice.
basic rule of shortening code write down first, quick , dirty, , see can replace shorter code snippet achieves same thing.
Comments
Post a Comment