Home > Mobile >  in python how can i write code to let the user enter the values of nested dictionary with list
in python how can i write code to let the user enter the values of nested dictionary with list

Time:04-07

{
    '1': {'s': ['2', '4'], 'c': ['3']},
    '2': { 's': ['5'] },
    '3': { 's': ['5'],'c': ['1']},
    '4': {'s': ['1'],'c': ['5'] },
    '5': {'s': ['2'], 'c': ['3']}


}

if i want the user input these values what is the correct code to do that and the user can enter different values every time run the code even the length of list inside the dictionary is changeable

i try this code but i don't know how let the user enter the values of dictionary with list because this code not get the values from user

myDict = dict()
list = ['1','2','3']
for n in list:
    for j in range(int(n), int(n)   2):
        myDict.setdefault(j, []).append(n)

print(myDict) 

CodePudding user response:

Have the user input the dictionary as JSON, and then you can just read it with json.loads():

import json
import pprint

myDict = json.loads(input("Enter data (JSON): "))
pprint.pprint(myDict)
Enter data (JSON): {"1": {"s": ["2", "4"], "c": ["3"]}, "2": { "s": ["5"] }, "3": { "s": ["5"],"c": ["1"]}, "4": {"s": ["1"],"c": ["5"] }, "5": {"s": ["2"], "c": ["3"]}}
{'1': {'c': ['3'], 's': ['2', '4']},
 '2': {'s': ['5']},
 '3': {'c': ['1'], 's': ['5']},
 '4': {'c': ['5'], 's': ['1']},
 '5': {'c': ['3'], 's': ['2']}}

CodePudding user response:

If you need the data to be interactive, where the user input each value at a time, you can try this:

def fun(data, alhabet, states):
  result = dict()
  for s in states:
    result[s] = dict()
    for a in alhabet:
      trs = input(f"Upon reading {a}, state {s} can be transmited to: ").split()
      if trs: result[s][a] = trs
  return result

print(fun(['s', 'c'], range(1, 6)))

The output is:

{1: {'s': ['2', '4'], 'c': ['3']},
 2: {'s': ['5']},
 3: {'s': ['5'], 'c': ['1']},
 4: {'s': ['1'], 'c': ['5']},
 5: {'s': ['2'], 'c': ['3']}}
  • Related