1

Objective:
1st number: Key to the second number
2nd number: Value to the first number but key to the third number
3rd number: Value to the second number

def make_dictionary_list(old_list):
    return {key: values for key, *values in old_list}

Input:
[(4157, 1, 1), (4157, 1, 10), (4157, 2, 1), (4157, 2, 10), (4157, 3, 1), (4157, 3, 10), (4157, 4, 1), (4157, 4, 10), (4182, 1, 1)]

Output:
{4157: [4, 10], 4182: [1, 1]}

The output is not what I want. As stated above, I'd like the 1st number being key to the 2nd number and 2nd number being the key to the 3rd number. How would I go about doing that?

Thanks!

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
ShadyBears
  • 3,955
  • 13
  • 44
  • 66

1 Answers1

2

You unravel your list and put it into a dictionary using dict.setdefault() :

data = [(4157, 1, 1), (4157, 1, 10), (4157, 2, 1), (4157, 2, 10), (4157, 3, 1), 
        (4157, 3, 10), (4157, 4, 1), (4157, 4, 10), (4182, 1, 1)]

d = {}
for k,v,p in data:
    key = d.setdefault(k,{})
    key[v]=p

print(d)

Output:

{4157: {1: 10, 2: 10, 3: 10, 4: 10}, 4182: {1: 1}}

You can acess it by:

print( d[4157][3] ) # 10

The result is shorter then your source-data because you replace the first value by the second one:

(4157, 1, 1) => (4157, 1, 10)  # 10 replaces 1  
(4157, 2, 1) => (4157, 2, 10)  # etc.
(4157, 3, 1) => (4157, 3, 10)
(4157, 4, 1) => (4157, 4, 10) 

You could instead aggregate them like so:

for k,v,p in data:
    key = d.setdefault(k,{})
    key2 = key.setdefault(v,[])
    key2.append(p)

print(d)

To get an output of:

{4157: {1: [1, 10], 2: [1, 10], 3: [1, 10], 4: [1, 10]}, 4182: {1: [1]}}

and access it by

print( d[4157][3] ) # [1, 10]
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • This is perfect. I've never heard of or used setdefault(). Great explanation! – ShadyBears Sep 15 '18 at 09:07
  • @juice - setdefault and dict.get(key [, defaultvalue] ) ( [why](https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey) )are both worth knowing when using dicts. Happy to be of help. You could also use [collections defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict) to the same effect, but I prefer "normal" dicts. – Patrick Artner Sep 15 '18 at 09:08
  • A hypothetical related follow-up question... if I had a fourth number that needed to be the value to the third number, would there be a better way to do this than having three "layers" of dictionaries? – ShadyBears Sep 16 '18 at 07:47