Skip to content
Advertisement

Calculate how many times the values are repeated inside a dictionary key

I have a dictionary that is created from a select in the database, what I needed was to generate a metric from that dictionary

Dictionary

 # create database dictionary with values
 lds_data = {}
 for lds_item in db_result:
 lds_data.update ({lds_item [1]: {'code_client': lds_item [0], 'city': lds_item [2]}})

Exit of the Dict:

 u'BRASIL_ALIMEN ': {' code_client ': u'BRA', 'city': u'SAO PAULO '},
 u'BRASIL_CARROS ': {' code_client ': u'BRC', 'city': u'PARANA '}

Example of metric:

code_client: BRA appears 1x within dictionary

Summing up:

I need to calculate how many times the values are repeated within the KEY = *code_client*

I tried to do it as follows:

 ct = {}
 for key in lds_data:
     ct ['code_client'] = len (lds_data [key] ['code_client'])

Advertisement

Answer

From what I can tell, you need to get a count of each code client in the dictionary. This code will populate the dictionary ct with each code_client as a key, and the number of occurrences as the value of each entry:

ct = {}
for _, value in lds_data.items():
    if value['code_client'] in ct:
        ct [value['code_client']] += 1
    else:
        ct [value['code_client']] = 1

EDIT: I would actually recommend using Austin’s answer. It’s effectively doing what I’m doing, but more correctly and succinctly.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement