python3 sorted()函数报错 TypeError: '<' not supported between instances of 'str' and 'int'

想对dict按值的大小进行排序。
我不明白的是,我明明在前面把所有非整形都转成整形了,它还是报类型错误。

dict = {}
for word in words:
    word=word.replace("\n","")
    body = {"query":{"bool":{"must":[{"range":{"time":{"gt":"2018-01-01","lt":"2019-01-01"}}},{"term":{"detailwords": word}}],"must_not":[],"should":[]}},"from":0,"size":20,"sort":[{"hot":"desc"}],"aggs":{}}
    res = es.search(index="events_v3", body=body)
    # print(res['hits']['hits'])
    for item in res['hits']['hits']:
        dict[item['_source']['desc']] = item['_source']['hot']

for key, value in dict.items():
    if type(value) != type(100):
        print("a")
        dict[key] = int(value)

    list1 = sorted(dict.values())

filename = 'abcd.json'
with open(filename, 'w', encoding='UTF-8') as f_obj1:
    json.dump(dict, f_obj1, ensure_ascii=False)

报的错误是:

Traceback (most recent call last):
File "G:/pycharm_workspace/ESDemo/demo1.py", line 24, in
list1 = sorted(dict.values())
TypeError: '<' not supported between instances of 'str' and 'int'

1个回答

去掉if type(value) != type(100):
全部强转
看下里面有没有空值

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问