我有很多行数据(我不能手动修改),它们被表示为一个键/值对的字典。问题是有一个字典键可以多次出现(对于未定义的数字:可能是两次、三次、十次等),具有不同的值。
我需要提取所有这些值。
这是一个简单的记录,其中包含键 Key-Word 的两个值:
{"Date": "Fri, 19 Apr 2019 00:54:46 GMT", "Vary": "Host,Accept-Encoding", "Key-Word": "00a", "Cache-Control": "private", "Key-Word": "xn"}
我编写了这个 python 脚本来提取记录的值。
import ast
import re
import json
inFile = open("sample.txt","r",errors="replace")
cP=0 # key found flag
cV=0 # hold the key's value
try:
myDict = {"Date": "Fri, 19 Apr 2019 00:54:46 GMT", "Vary": "Host,Accept-Encoding", "Key-Word": "00a", "Cache-Control": "private", "Key-Word": "xn"}
smallmyDict= {}
except (ValueError, SyntaxError) as E:
cV="error"
except Exception as E:
cV="error"
# convert the header's key to small letter
for key, value in myDict.items():
smallmyDict[key.lower()] = value
# store all keys
smallmyDictKeys =smallmyDict.keys()
# search for a specific key
if 'key-word' in smallmyDictKeys:
cP=1
cV = smallmyDict['key-word']
print("Found!")
print(cV) #print the key's value
else:
print("NOT Found!")
我得到的输出是:
Found! xn
问题是它只打印最后一个键的值。
如果我要查找的键多次出现并单独打印每个值而不是用最后一个值覆盖它,我如何让我的代码迭代它?
请您参考如下方法:
您可以使用json 来解析您的数据,并使用json.loads 的object_pairs_hook 参数。个性化数据处理。在下面的示例中,我将相同键的不同值分组在一个列表中(并且,按照您评论中的要求,将它们连接成一个字符串):
import json
from collections import Counter, defaultdict
data = """{"Date": "Fri, 19 Apr 2019 00:54:46 GMT", "Vary": "Host,Accept-Encoding", "Key-Word": "00a", "Cache-Control": "private", "Key-Word": "xn"}
"""
def duplicate_keys(pairs):
out = {}
dups = defaultdict(list)
key_count = Counter(key for key, value in pairs)
for key, value in pairs:
if key_count[key] == 1:
out[key] = value
else:
dups[key].append(value)
# Concatenate the lists of values in a string, enclosed in {} and separated by ';'
# rather than in a list:
dups = {key: ';'.join('{' + v + '}' for v in values) for key, values in dups.items()}
out.update(dups)
return out
decoded = json.loads(data, object_pairs_hook=duplicate_keys)
print(decoded)
# {'Date': 'Fri, 19 Apr 2019 00:54:46 GMT',
# 'Vary': 'Host,Accept-Encoding',
# 'Cache-Control': 'private',
# 'Key-Word': '{00a};{xn}'}
