Search code examples
pythonpython-3.xdictionary-comprehension

List comprehension - attempting to create dictionary from array of key-value pair arrays


While trying to create a dict using list comprehension (without overwriting generated list keys)

x = {}
entries = [[1,'1a'], [2,'2a'], [3,'3a'], ['1', '1b'], ['2', '2b'], ['3', '3b']]
discardable = [x.setdefault(entry[0], []).append(entry[1]) for entry in entries]

Error: name 'x' is not defined

I was expecting x to be populated as:

{1: ['1a', '1b'], 2: ['2a', '2b'], 3: ['3a', '3b']}

How to explain this / make this work? Is there any other way to achieve this?


Solution

  • Some of the keys are str and some are int, so this will produce

    {'1': ['1a', '1b'], 2: ['2a'], 3: ['3a'], '2': ['2b'], '3': ['3b']}
    

    You need to cast entry[0] to int

    x = {}
    entries = [[1,'1a'], [2,'2a'], [3,'3a'], ['1', '1b'], ['2', '2b'], ['3', '3b']]
    [x.setdefault(int(entry[0]), []).append(entry[1]) for entry in entries]
    

    print(x) will give

    {1: ['1a', '1b'], 2: ['2a', '2b'], 3: ['3a', '3b']}