用json fi上的值创建字典

2024-05-14 10:48:41 发布

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

我需要从这个json文件的不同对象中获取两个值,并用它们生成dict,求int值的和。我得到的第一个值如下:

for d in data:
    for (date, details) in d['nightlyDetails'].items():
        for (key, value) in details.items():
            if key == 'accountLabelType':
                print(key,value)

但是我想制作一个字典,用defaultdict来生成一个集合,这样每个键名只有一个,然后是总的求和值。如何获取totalRent值并求和,然后生成一个dict,每个dict只包含一个键并求和这些值?你知道吗

以下是json文件的外观:

"checkOut": "2016-02-04",
  "sourceBusinessName": "xxxx.com",
  "folioStatusIdUserDef": "0",
  "discounts": 0,
  "reservationDate": "2015-06-30 07:13:11",
  "additionalGuestIds": [],
  "lastNightAuditDate": "0000-00-00",
  "adjustmentTotal": 0,
  "totalRent": 1280,
  "noOfSplits": 1,
  "checkoutDate": "2016-02-04 10:19:30",
  "noOfNights": 1,
  "folioNo": "44108",
  "pm_code": "",
  "arrivalAmpm": "am",
  "folioStatus": "Checked-Out",
  "checkinBy": "xxxx",
  "reservedBy": "Oboe Reservation",
  "event_training_id": "0",
  "housekeepingRuleId": "0",
  "occupancyAdults": "2",
  "nightlyDetails": {
    "2016-02-03": {
      "accountLabelId": 1,
      "accountCategoryId": 6,
      "NightlyOverrideType": "0",
      "accountCategoryType": "Add-on",
      "NightlyRoomTransferId": "0",
      "accountLabelType": " Rooms \u74e6\u5382\u623f\u95f4",
      "NightlyRateId": "196",
      "NightlyActualPrice": "1280.000000",
      "NightlydiscountType": "0",
      "NightlyOverride": "0.000000",
      "rateName": "SQ",
      "NightAuditDate": "0000-00-00",
      "NightlyPaidByGroup": "0",
      "NightlyOfferedPrice": "1280.000000",
      "Nightlydiscount": "0.00",
      "NightlyActualDiscountPrice": 1280
    }

我真正需要的是这样的口述:

Homes:10000
Rooms:3500

因此,dict只包含每个accountLabelType中的一个,以及每个类型的所有totalRent值的总和。这个json只是一个演示,因为它非常长。它重复了很多次,就像预订房间一样多。你知道吗


Tags: 文件对象keyinjsonforvalueitems
3条回答

不太清楚你在问什么但是。。。你知道吗

from operator import itemgetter
ig = itemgetter('totalRent')
rents = map(ig, data)
totalRent = sum(rents)

这就是如何从整个datadict得到totalRent值的总和。你知道吗

我不太明白你为什么想要一个defaultdict。 除非要提取除totalRent以外的更多值。你知道吗

你可能想更精确一点,你实际上想要从数据中得到什么。 比如给我们一个输出应该是什么样的示例字典。你知道吗

我假设您已经将JSON文件解析为字典列表data。我总结了dict中每个accountLabelTypetotalRent值:

totalRent_dict = {}

for d in data:
    accountLabelType = None
    for (date, details) in d['nightlyDetails'].items():
        for (key, value) in details.items():
            if key == 'accountLabelType':
                accountLabelType = value
    if accountLabelType:
        try:
            totalRent_dict[accountLabelType] += d['totalRent']
        except KeyError:
            totalRent_dict[accountLabelType] = d['totalRent']

使用the Python ^{} module。你知道吗

import json

Dict = json.load(open(file_name))

那么Dict就是一本字典。你知道吗

相关问题 更多 >

    热门问题