Home > Software engineering >  How to create a dictionary from list with single for loop?
How to create a dictionary from list with single for loop?

Time:01-19

List is a = [1,2,3]

How to get the dictionary from that list like below?

{1: 1, 1: 2, 1: 3, 2: 1, 2: 2, 2: 3, 3: 1, 3: 2, 3: 3}

Condition is to do not use two for loops.

It was asked in an interview, but I was not able to implement without two for loops so I thought interviewer might be wrong.

Note: List a is of variable length

CodePudding user response:

The example that you provide would not work. As @Mark suggests, try putting the desired dictionary into an interpreter:

>>> {1: 1, 1: 2, 1: 3, 2: 1, 2: 2, 2: 3, 3: 1, 3: 2, 3: 3}
{1: 3, 2: 3, 3: 3}

This is because, according to Python documentation,

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

First pair creates a dictionary {1: 1}. Then next pair updates it: {1: 2}, etc. So, by the end, you will be left with the last pair with a given key (for each key).

CodePudding user response:

Cartesian product:

from itertools import product

a = [1,2,3]
list(product(a, a))

Btw, this result is not a "valid" dict because of duplicate keys.

  • Related