dictionary update()仅在python中从目录中不同文件添加多个字典时保留最后一个字典



我有一个包含多个JSON文件的目录。每个JSON文件都有一个JSON结构(每个结构中有3个字典元素)。我想读取每个JSON文件,并将字典附加到单个dictionary中-一个主dictionary,其中包含所有字典。这是我的代码:

def json_read:
pathToDir = '/path/to/directory'
json_mstr = {}
for file_name in [file for file in os.listdir(pathToDir) if file.endswith('.json')]:
with open(pathToDir + file_name) as input_file:
print(file_name)
json_str = json.load(input_file)
json_mstr.update(json_str)
print(len(json_mstr))

return json_mstr

当我打印长度时,我只看到3作为最终主dictionary的长度,并且只有主dictionary中最后一个JSON文件的字典内容。不知道为什么update()在每个文件读取后重置字典?

注意JSON在每个文件中的结构示例如下:

{
"resourceType": "Single",
"type": "transaction",
"entry": [
{
"fullUrl": "urn:uuid",
"resource": {
"resourceType": "Employee",
"id": "4cb1a87c",
"text": {
"status": "generated",
"div": "generated"
},
"extension": [],
"identifier": [
{
"system": "https://github.com",
"value": "43f123441901"
}
],
"name": [
{
"use": "official",
"family": "Shields52",
"given": [
"Aaro97"
],
"prefix": [
"Mr."
]
}
],
"maritalStatus": {
"coding": [
{
"system": "MaritalStatus",
"code": "M",
"display": "M"
}
],
"text": "M"
},
"multipleBirthBoolean": false
},
"request": {
"method": "POST",
"url": "User"
}
},
{
"fullUrl": "f411764e1f01",
"resource": {
"resourceType": "Claim",
"id": "411764e1f01",
"status": "active",
"type": {
"coding": [
{
"system": "type",
"code": "Company"
}
]
},
"use": "claim",
"employee": {
"reference": "1141dfb308"
},
"billablePeriod": {
"start": "2009-12-24T16:42:36-05:00",
"end": "2009-12-24T16:57:36-05:00"
},
"created": "2009-12-24T16:57:36-05:00",
"provider": {
"reference": "7e31e2b3feb"
},
"priority": {
"coding": [
{
"system": "Employee",
"code": "normal"
}
]
},
"procedure": [
{
"sequence": 1,
"procedureReference": {
"reference": "58f373a0a0e"
}
}
],
"insurance": [
{
"sequence": 1,
"focal": true,
"coverage": {
"display": "Employer"
}
}
],
"item": [
{
"sequence": 1,
"productOrService": {
"coding": [
{
"system": "http://comp1.info/",
"code": "1349003",
"display": "check up"
}
],
"text": "check up"
},
"encounter": [
{
"reference": "bc0a5705f6"
}
]
},
{
"sequence": 2,
"procedureSequence": [
1
],
"productOrService": {
"coding": [
{
"system": "http://comp.info",
"code": "421000124101",
"display": "Documentation"
}
],
"text": "Documentation"
},
"net": {
"value": 116.60,
"currency": "USD"
}
}
],
"total": {
"value": 163.7,
"currency": "USD"
}
},
"request": {
"method": "POST",
"url": "Employee"
}
}
]
}

字典是键值映射。update将覆盖相同的键。

d1 = {1: 1, 2: 2}
d1.update({1: 2, 3: 3}) # value for key 1 will be replaced
print(d1) # {1: 2, 2: 2, 3: 3}

如果你想在一个字典中有3个字典,给它们一些键,例如filename:

for file_name in [file for file in os.listdir(pathToDir) if file.endswith('.json')]:
with open(pathToDir + file_name) as input_file:
json_mstr[file_name] = json.load(input_file)

最新更新