Luis Henrique
Luis Henrique

Reputation: 771

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'])

Upvotes: 2

Views: 845

Answers (3)

Ahndwoo
Ahndwoo

Reputation: 1025

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.

Upvotes: 0

Austin
Austin

Reputation: 26039

Use Collections.Counter:

from collections import Counter

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

c = Counter(v[' code_client '] for _, v in d.items())

print(c['BRA'])
# 1

If you print c, you will see that it has got counts of each value of ' code_client '. That makes this flexible, maybe some day in future you require the count of 'BRC'.

Upvotes: 3

Prune
Prune

Reputation: 77827

I don't think this works; how does it handle the case with

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

You now have BRA in your code two times, but your count is not updated.

Instead, build a list of the values under code_client in the list of dicts, such as

client_list = [inner_dict['code_client'] for inner_dict in lds_data]

Now, make a collections.Counter of this list.

Can you finish from there?

Upvotes: 1

Related Questions