[Python] dynamically populating a dictionary [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 8, 2025.

  1. Stack

    Stack Membro Participativo

    Trying to work with nested dictionaries.... Taking input from user about how many input items he has with him(he enters a no), for each item, the code asks him to enter two numbers, from which, the code shall tell the largest and lower number in the range of nos entered...

    PFB Code:

    def how_many_sets():
    global set_nos_list
    set_nos_list = []
    defaults = {"range": [], "items": [], "largest": 0, "lowest": 0, "difference": 0}
    global set_no
    set_no = int(input('How many sets?'))
    if set_no < 1 or set_no > 10:
    print('error')
    else:
    for num in range(set_no):
    set_nos_list.append(num)
    print(set_nos_list)
    global set_dict
    set_dict = dict.fromkeys(set_nos_list, defaults)
    return set_no


    def take_sets():
    for item in set_nos_list:
    list_per_pair = list(map(int, input().split()))
    if len(list_per_pair) != 2:
    print('There is an error in the no of items, For finding the range two items should be there in a list')
    return
    elif (list_per_pair[0] < 2) or (list_per_pair[1] > 1000000) or (list_per_pair[0] > list_per_pair[1]):
    print(' error')
    return
    else:
    print(item)
    set_dict[item]["range"] = list_per_pair
    temp_item_list = []
    for value in range(list_per_pair[0], list_per_pair[1] + 1):
    # print(value)
    temp_item_list.append(value)
    print(temp_item_list)
    #set_dict[num]['items'] = temp_item_list

    print(set_dict)


    def main():
    how_many_sets()
    take_sets()


    # Write code here

    main()


    The line set_dict[item]["range"] = list_per_pair gives me an error, the set_dict gets updated with the last item value only despite the loop being iterating over all values....

    How many sets?2
    [0, 1]
    3 6
    0
    [3, 4, 5, 6]
    4 7
    1
    [4, 5, 6, 7]
    {0: {'range': [3, 6], 'items': [], 'largest': 0, 'lowest': 0, 'difference': 0}, 1: {'range': [4, 7], 'items': [], 'largest': 0, 'lowest': 0, 'difference': 0}}


    where as I want output something like this:

    {0: {'range': [4, 7], 'items': [], 'largest': 0, 'lowest': 0, 'difference': 0}, 1: {'range': [4, 7], 'items': [], 'largest': 0, 'lowest': 0, 'difference': 0}}

    Continue reading...

Compartilhe esta Página