Coder117
Coder117

Reputation: 851

Python List into a Dict?

I have a program that reads in two (or three) whitespace delimited tokens, 2 strings, and optionally, a number, per line

My program:

import sys
d = sys.stdin.readlines()
d = [i.split() for i in d]
print(*d)

Running the program:

python3 program12.py
Austin Houston 300
SanFrancisco     Albany         1000
NewYorkCity    SanDiego
['Austin', 'Houston', '300'] ['SanFrancisco', 'Albany', '1000'] ['NewYorkCity', 'SanDiego']

But now I need to add these items into a dict, which is where I get confused: For the example input, the dict would need to look like this:

{'Austin': {'Houston': 300}, 'SanFrancisco':  {'Albany': 1000}, 'NewYorkCity': { 'SanDiego': True }}

Dicts are still confusing to me on how they even work, let alone filling one up with what seems like a nested dict. Any help is appreciated!

Upvotes: 1

Views: 82

Answers (2)

Sraw
Sraw

Reputation: 20214

update

One line better solution.

d = {e[0] : {e[1] : e[2] if len(e) == 3 else True} for e in d}


update

I ignored that your last element's length is just two, so if you could build the list like this [['Austin', 'Houston', '300'],['SanFrancisco', 'Albany', '1000'],['NewYorkCity', 'SanDiego', True]], then the solution below could work.


One line solution.

d = {e[0] : {e[1] : e[2]} for e in d}

Upvotes: 3

Sumeet P
Sumeet P

Reputation: 154

d = { e[0]: {e[1]: (e[2] if e[2:] else True)} for e in d}

Add this one line at the end.

Upvotes: 2

Related Questions