user12904074
user12904074

Reputation:

how to group by keys with respect of some part of values in python?

I have a json file with keys and Results . The result has 3 parts. like this:

df.json()[0]['Results'][0]

{'categoryId': '2674',
 'categoryName': 'software engineer',
 'score': '1.0377672767639161'}

I want to collect all keys who have the same categoryName in the result. and then count them. Is it possible?

Upvotes: 0

Views: 45

Answers (1)

user14226448
user14226448

Reputation:

One way of doing it would be iterating over every group in one of the following ways: if you just want to know the count of one group you can do this:

category_name = "software engineer"
count = 0
for cat in df.json()[0]['Results']:
    if cat['categoryName'] == category_name:
        count += 1

If you want to count all categories at the same time you can do that as well:

category_count = {}
for cat in df.json()[0]['Results']:
   category = cat['categoryName']
   if category in category_count.keys():
       category_count[category] += 1
    else:
        category_count[category] = 1

to get the corresponding keys you can do:

category_count = {}
for key, cat in enumerate(df.json()[0]['Results']):
   category = cat['categoryName']
   if category in category_count.keys():
       category_count[category].append(key)
    else:
        category_count[category] = [key]

that way you can get all keys with the categoryName="software engineer" like this: category_count["software_engineer"]

Upvotes: 2

Related Questions