查找值在pythondi中出现的次数

2021-06-14 23:19:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用嵌套词典:

{
"payload": {
    "existence_full": 1,
    "geo_virtual": "[\"56.9459720|-2.1971226|20|within_50m|4\"]",
    "latitude": "56.945972",
    "locality": "Stonehaven",
    "_records_touched": "{\"crawl\":8,\"lssi\":0,\"polygon_centroid\":0,\"geocoder\":0,\"user_submission\":0,\"tdc\":0,\"gov\":0}",
    "address": "The Lodge, Dunottar",
    "email": "dunnottarcastle@btconnect.com",
    "existence_ml": 0.5694238217658721,
    "domain_aggregate": "",
    "name": "Dunnottar Castle",
    "search_tags": [
        "Dunnottar Castle Aberdeenshire",
        "Dunotter Castle"
    ],
    "admin_region": "Scotland",
    "existence": 1,
    "category_labels": [
        [
            "Landmarks",
            "Buildings and Structures"
        ]
    ],
    "post_town": "Stonehaven",
    "region": "Kincardineshire",
    "review_count": "719",
    "geocode_level": "within_50m",
    "tel": "01569 762173",
    "placerank": 65,
    "longitude": "-2.197123",
    "placerank_ml": 37.27916073464469,
    "fax": "01330 860325",
    "category_ids_text_search": "",
    "website": "http://www.dunnottarcastle.co.uk",
    "status": "1",
    "geocode_confidence": "20",
    "postcode": "AB39 2TL",
    "category_ids": [
        108
    ],
    "country": "gb",
    "_geocode_quality": "4"
},
"uuid": "3867aaf3-12ab-434f-b12b-5d627b3359c3"
}

我得记下“博物馆”在字典里出现的次数。我在下面写的代码不会打印任何东西,我不知道我遗漏了什么。有没有其他方法可以遍历dict中的所有值并计算某个值出现的次数?你知道吗

museum = {}
for i in range (0, len(json_file)):
    try: 
        record = json_file[i]['payload']
        for value in record.values():
            if value == 'Museum':
                museum +=1 
                print(museum)
    except:
        continue
2条回答
网友
1楼 ·

这个怎么样?你知道吗

import json
museum_count = 0
data = json.load(json_file)
for x in data:
    try:
        for value in data[x]['payload']:
            if value.lower() == "museum":
                museum_count+= 1
    except KeyError, e:
        print str(e)

您的代码未命中KeyError异常。如果只使用exception,代码就会一直运行(并跳过所有内容),而不会告诉您。如其他人所说:

museum = {}

声明一个字典,要计算或处理数字,需要一个整数。您可以声明整数,例如:

my_int = 0
网友
2楼 ·

代码museum = {}声明了一个字典。 运行代码museum +=1时,应该会出现以下错误:

TypeError: unsupported operand type(s) for +=: 'dict' and 'int'

如果你想要一个计数器,那么做类似museum = 0

相关问题