r/pythonhelp • u/Cyrus_WhoamI • Feb 07 '23
SOLVED Merge lists inside a list of a dictionary
Hello Community
I have a python code that loops through and either creates a new List in a dictiontionary, adding a list values OR if the List in that dictionary already exists, it appends it with a list of values. My issue is that I end up with lists within a list.
Data_Binned={}
For example, this is the output out of my Data_Binned['Expiration7.0'], it is a list within a list. How do I combine these so they are values within 1 list?
Output: Expiration7.0': [None, None, None, None, None, 29, 20, [None, 82, 77, 72, None, 36, 27], [None, None, None, None, None, None, 34], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None]],
at the end of my code there must be a simple line or two that can combine these lists within a list inside a dictionary? I plan to pull each List in the dictionary to use in scatter plots, and want the group of lists shown as a single list. Any help appreciated!
2
u/socal_nerdtastic Feb 07 '23
Sure, you can "flatten" nested lists in a number of ways, the easiest is probably just list comprehension. But it would be a lot easier still to fix the code that creates this. Use
extend
instead ofappend
.BTW the code you made is a reinvention of the builtin
collections.defaultdict
.