I have a dictionary like that:
dic = {'a':[['1'],['4']],'b':['1'],'c':['2']}
and I would like to remove the un-necessary lists to get:
newdict={'a':['1','4'],'b':'1','c':'2'}
How can I do that? Thanks!
I have a dictionary like that:
dic = {'a':[['1'],['4']],'b':['1'],'c':['2']}
and I would like to remove the un-necessary lists to get:
newdict={'a':['1','4'],'b':'1','c':'2'}
How can I do that? Thanks!
Well, if you are not concerned about speed or efficiency, I suppose this could work:
def flatten(l):
'''
Function to flatten a list of any level into a single-level list
PARAMETERS:
-----------
l: preferably a list to flatten, but will simply create a single element list for others
RETURNS:
--------
output: list
'''
output = []
for element in l:
if type(element) == list:
output.extend(flatten(element))
else:
output.append(element)
return output
dic = {'a':[[[['1'],['4']]],'3'],'b':['1'],'c':['2']}
newdict = {key: flatten(value) for key, value in dic.items()}
print(newdict)
gives, as expected:
{'a': ['1', '4', '3'], 'b': ['1'], 'c': ['2']}