Перебирать большой словарь в PythonPython

Программы на Python
Anonymous
Перебирать большой словарь в Python

Сообщение Anonymous »

Я написал эту функцию для объединения значений налогов на основе определенной логики. Он перебирает налоговый словарь в поисках ключей, которые имеют общий суффикс кода страны и имеют перекрывающиеся значения. При обнаружении таких ключей их значения объединяются, а дубликат ключа удаляется из словаря.

Код: Выделить всё

def merge_tax_values_new_logic(tax_dict):
treated_list = set()
while True:
changed = False
for key1, value1 in list(tax_dict.items()):
country_code = key1[-2:]
print('current list :',tax_dict)
if key1 not in treated_list:
print('current iteration key :' , key1)
for key2, value2 in list(tax_dict.items()):
if key2.endswith(country_code) and key1 != key2 and any(hl_id in value2 for hl_id in value1):
tax_dict[key1].extend(value2)
tax_dict.pop(key2)
tax_dict[key1] = list(set(tax_dict[key1]))
changed = True
print( 'current key : ' , key1 , 'matched  with key : ' , key2  ,  'state  of the dict after the pop : ', tax_dict)
break
treated_list.add(key1)
print('treated list :', treated_list)
print('******************************')
if changed:
break
if not changed:
break
return tax_dict
Пример:

Код: Выделить всё

new_tax_dict = {'tax1_US':['A'],'tax2_US':['B'], 'tax3_US':['A','B']}
merge_tax_values_new_logic(new_tax_dict)
Результат:

Код: Выделить всё

    current list : {'tax1_US': ['A'], 'tax2_US': ['B'], 'tax3_US': ['A', 'B']}
current iteration key : tax1_US
current key :  tax1_US matched  with key :  tax3_US state  of the dict after the pop :  {'tax1_US': ['A', 'B'], 'tax2_US': ['B']}
treated list : {'tax1_US'}
******************************
current list : {'tax1_US': ['A', 'B'], 'tax2_US': ['B']}
treated list : {'tax1_US'}
******************************
current list : {'tax1_US': ['A', 'B'], 'tax2_US': ['B']}
current iteration key : tax2_US
current key :  tax2_US matched  with key :  tax1_US state  of the dict after the pop :  {'tax2_US': ['A', 'B']}
treated list : {'tax2_US', 'tax1_US'}
******************************
current list : {'tax2_US': ['A', 'B']}
treated list : {'tax2_US', 'tax1_US'}
******************************
{'tax2_US': ['A', 'B']}
он ​​отлично работает с небольшими словарями с несколькими ключами. Однако производительность является реальной проблемой, когда эта функция имеет дело с большим количеством ключей внутри словаря (+40 тысяч ключей и среднее количество значений 5 элементов для каждого ключа).
Вы знаете? видите ли другие альтернативы?
С уважением,

Подробнее здесь: https://stackoverflow.com/questions/783 ... -in-python

Вернуться в «Python»