Итерация и индексирование через словарь Python

#python-3.x #function #dictionary #for-loop #indexing

Вопрос:

Приведенный ниже код проходит через словарь и выводит подмножества того dictionary , что включает CompoundedAmount,TradingPair,talib_function в себя . Однако из-за вложенного цикла for counter он сбрасывается по мере прохождения двух подуровней для печати выходных данных. Вместо того, чтобы использовать вложенные циклы for, как бы я мог получить Expected Output , где counter не сбрасывается, и он проходит sets по порядку?

 def Indexing(dictionary):
    for index,Value in dictionary.items():
        for counter,(sets) in enumerate(Value):
            print("counter: ",  counter, "sets: ",sets)

    
dictionary = { 
 'RSI': [{'CompoundedAmount': 2,
          'TradingPair': 'BTCUSD',
          'talib_function': 'RSI'},
         {'CompoundedAmount': 2,
          'TradingPair': 'XRPUSD',
          'talib_function': 'RSI'}],
 'ROCR100': [{'CompoundedAmount': 2,
              'TradingPair': 'BCHUSDT',
              'talib_function': 'ROCR100'}],
 'MOM': [{'CompoundedAmount': 2,
          'TradingPair': 'BCHUSDT',
          'talib_function': 'MOM'}]}

Indexing(dictionary)
 

Выход:

 counter:  0 sets:  {'CompoundedAmount': 2, 'TradingPair': 'BTCUSD', 'talib_function': 'RSI'}
counter:  1 sets:  {'CompoundedAmount': 2, 'TradingPair': 'XRPUSD', 'talib_function': 'RSI'}     
counter:  0 sets:  {'CompoundedAmount': 2, 'TradingPair': 'BCHUSDT', 'talib_function': 'ROCR100'}
counter:  0 sets:  {'CompoundedAmount': 2, 'TradingPair': 'BCHUSDT', 'talib_function': 'MOM'} 
 

Ожидаемый результат:

 counter:  0 sets:  {'CompoundedAmount': 2, 'TradingPair': 'BTCUSD', 'talib_function': 'RSI'}
counter:  1 sets:  {'CompoundedAmount': 2, 'TradingPair': 'XRPUSD', 'talib_function': 'RSI'}     
counter:  2 sets:  {'CompoundedAmount': 2, 'TradingPair': 'BCHUSDT', 'talib_function': 'ROCR100'}
counter:  3 sets:  {'CompoundedAmount': 2, 'TradingPair': 'BCHUSDT', 'talib_function': 'MOM'} 
 

Комментарии:

1. Вместо enumerate() этого вы можете поддерживать counter вне первого цикла, который будет увеличиваться каждый раз во втором цикле

Ответ №1:

Просто используйте другую переменную:

 def Indexing(dictionary):
    count = 0
    for index, Value in dictionary.items():
        for sets in Value:
            count  = 1
            print("counter: ",  count, "sets: ",sets)

Indexing(dictionary)

counter:  1 sets:  {'CompoundedAmount': 2, 'TradingPair': 'BTCUSD', 'talib_function': 'RSI'}
counter:  2 sets:  {'CompoundedAmount': 2, 'TradingPair': 'XRPUSD', 'talib_function': 'RSI'}
counter:  3 sets:  {'CompoundedAmount': 2, 'TradingPair': 'BCHUSDT', 'talib_function': 'ROCR100'}
counter:  4 sets:  {'CompoundedAmount': 2, 'TradingPair': 'BCHUSDT', 'talib_function': 'MOM'}
 

Ответ №2:

Вы не можете использовать enumerate , потому counter что равно нулю при каждом запуске вложенного цикла. Вы можете использовать этот:

 def Indexing(dictionary):
    counter = 0
    for index,Value in dictionary.items():
        for (sets) in Value:
            print("counter: ",  counter, "sets: ",sets)
            counter  = 1