Dhruv Pillai
Dhruv Pillai

Reputation: 112

How to iterate through list and populated nested dictionary Python?

I am attempting to create a nested dictionary, and want to populate it with arguments passed to my Python script from the command line. I want each entry in the command line to be a key in the dictionary, and the dictionary will terminate with the value of the last command line argument. The 'root' key in the dictionary will be the 2nd argument passed to the command line (in index 0, the root key would be sys.argv[1]). I am looking for something like this:

./script.py arg1 arg2 arg3 arg4 arg5

resulting in the dictionary:

{arg1: {arg2: {arg3: {arg4: arg5}}}}

Here's what I have so far:

parameter = {}
parameter[sys.argv[-2]] = sys.argv[-1]
for i in reversed(sys.argv[1:-2]):
    print(parameter)
    parameter[i] = parameter

which results in the output:

{'arg2': {...}, 'arg1': {...}, 'arg3': {...}, 'arg4': 'arg5'}

Upvotes: 0

Views: 142

Answers (3)

Ajax1234
Ajax1234

Reputation: 71451

You are assigning the dictionary to itself, thus the resulting {...} syntax. You can try this instead:

import sys
args = sys.argv[1:]
d = {}
def place(l, last):
   if not l[1:]:
      return {l[0]:last}
   else:
      return place(l[1:], {l[0]:last})
print(place(args[::-1], args[-1]))

Output:

{'arg1': {'arg2': {'arg3': {'arg4': {'arg5': 'arg5'}}}}}

Upvotes: 1

magu_
magu_

Reputation: 4856

I would do this with recursion. An easy example would be:

import sys

def create_dict(items):
    if len(items) == 1:
        return items[0]
    else:
        return {items[0]: create_dict(items[1:])}

if __name__ == '__main__':
    result = create_dict(sys.argv[1:])
    print(result)

Upvotes: 3

NiVeR
NiVeR

Reputation: 9786

This function is suited for recursive solution. Process the arguments from the first to the last and at each step map the current argument to the result of the function itself. You do this until you come to the last element, which you simply return.

Upvotes: 1

Related Questions