Search code examples
pythonarrayspython-3.xdictionary

How to get all of the array values out of a dictionary of lists as a list?


I have a dictionary of arrays of the following format:

letters = {1: ['h'], 2: ['e'], 3: ['l', 'l'], 4: ['o']}

I'd like to know how I can get all of the values out of the arrays within the letters dict, bearing in mind that there may be single or multiple values within each one and the array values may be duplicates. So for the above example, I'd want the following output:

letter_values = ['h', 'e', 'l', 'l', 'o']

although the output needn't necessarily be in order.

I know how to get the values out of a dictionary using dict.values(), but not when there is an additional layer of abstraction like this.


Solution

  • While writing this question (as is often the case), I figured out the answer.

    You just need to use the dict.values() functionality to obtain a list of lists, and then concatenate those lists (for which there is a convenient shorthand), like so:

    letter_values = [item for sublist in letters.values() for item in sublist]
    

    Where item and sublist are just throwaway variables.

    Easy!

    (A reminder)