user391
user391

Reputation: 105

Coverting List to Dictionary in Python

How can I convert a python list to a dictionary by comparing value at index 2 and 3 respectively

['Tunnel0', 'up', 'up'] --> {'Tunnel0':'1'}
['Tunnel0', 'up', 'down']--> {'Tunnel0':'0'}
['Tunnel0', 'down', 'down']--> {'Tunnel0':'0'}
['Tunnel0', 'down', 'up']--> {'Tunnel0':'0'}

Any help is much appreciated?

Here is what I tried

a = ['Tunnel0', 'up', 'up']
TunnelStatus = {i:1 if a[1]==a[2] else 0 for i in a }
print(TunnelStatus)
>>>{'Tunnel0': 1, 'up': 1}

b = ['Tunnel0', 'up', 'down']
TunnelStatus = {i: 1 if b[1]==b[2] else 0 for i in b }
print(TunnelStatus)
>>>{'Tunnel0': 0, 'up': 0, 'down': 0}

Upvotes: 0

Views: 120

Answers (2)

Isdj
Isdj

Reputation: 1856

It is unclear to me whether you want a general solution for a list of length 3n or specifically for a list of 3 strings.

This will provide the solution in any case:

TunnelStatus = {a[i]:1 if a[i+1] == a[i+2] == 'up' else 0 for i in range(0, len(a), 3)}

This comprehension iterates in jumps of 3 comparing the i+1 and i+2 variables.

Here is some output:

a = ['tunnel0','up','up','tunnel1','up','down','tunnel2','down','up',
    'tunnel3','down','down']
b = ['tunnel0','up','up']

{a[i]:1 if a[i+1] == a[i+2] == 'up' else 0 for i in range(0, len(a), 3)}
>>>{'tunnel0': 1, 'tunnel1': 0, 'tunnel2': 0, 'tunnel3': 0}

{b[i]:1 if b[i+1] == b[i+2] == 'up' else 0 for i in range(0, len(b), 3)}
>>>{'tunnel0': 1}

In your solution you are iterating over the whole list and comparing the constants a[1] and a[2]. Thus, You will receive multiple output keys in the dictionary with all values equal.

Upvotes: 2

oppressionslayer
oppressionslayer

Reputation: 7204

You can use counter and create a list of dicts:

from collections import Counter
s = [['Tunnel0', 'up', 'up'],
['Tunnel0', 'up', 'down'],
['Tunnel0', 'down', 'down'],
['Tunnel0', 'down', 'up']]

d=[]
for item in s:
  if Counter(item)['up'] == 2:
     d.append({item[0]: 1})
  else:
     d.append({item[0]: 0})

d

output:

 [{'Tunnel0': 1}, {'Tunnel0': 0}, {'Tunnel0': 0}, {'Tunnel0': 0}]

Upvotes: 0

Related Questions