如何在具有相同名称的不同键中添加值

2024-06-26 01:50:41 发布

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

以下是我的数据:

{
"data": [
  {
    "date": 1577836800000,
    "@NOTIFICATION_SENT": 62629,
    "@NOTIFICATION_OPENED": 404
},
{
   "date": 1577923200000,
   "@NOTIFICATION_OPENED": 734
  }
 ]
}

如何添加所有@NOTIFICATION\u OPENED”键以在同一字符串中打开所有notif?如果不可能,如何仅选择第一个键“@NOTIFICATION\u OPENED”

使用我的代码,我打印最后一个重复密钥的值

这是我的密码:

    def create_json(id, notificationSent, notificationOpened):
return {(id):{
    'id': id,
    'notificationSent': notificationSent,
    'notificationOpened': notificationOpened,
    }}

    statUrl = 'myapiurl'
    with urlopen (statUrl) as response: sourcedata = response.read()
    statdata = json.loads (sourcedata)

   def push_data():
    newJsonx = dict()
   for item in data["data"]:
    for item in statdata["data"]:
        try:
            notificationOpened = item["@NOTIFICATION_OPENED"]
        except:
            notificationOpened = '0'
        print(notificationOpened)
        try:
            notificationSent = item["@NOTIFICATION_SENT"]
        except:
            notificationSent = '0'
    # JSON DATA
    newJson = create_json(notificationSent, notificationOpened)
    newJsonx.update(newJson)

    with open('myfile.json', 'w', encoding='utf-8') as json_file:
    json.dump(newJsonx, json_file, ensure_ascii=False, sort_keys=True, indent=2)

print('JSON: %s' % json.dumps(newJsonx, sort_keys=True, indent=2))

push_data()

Tags: idjsondatadatedefcreatewithnotification
2条回答
# ...snipped for brevity...

with urlopen(statUrl) as response: 
    sourcedata = response.read()
    statdata = json.loads(sourcedata)

print(statdata)
# should be this format as in your question post 
# {
#     "data": [{
#                 "date": 1577836800000,
#                 "@NOTIFICATION_SENT": 62629,
#                 "@NOTIFICATION_OPENED": 404
#             },
#             {
#                "date": 1577923200000,
#                "@NOTIFICATION_OPENED": 734
#             }]
# }

notificationSent = []
notificationOpened = []

for i, d in enumerate(statdata['data']):
    notificationOpened.append(d.get('@NOTIFICATION_OPENED', 0))
    notificationSent.append(d.get('@NOTIFICATION_SENT', 0))

print(sum(notificationOpened))

1138

这里是原始代码的变体,它将创建您要查找的词典

# create data
statdata = {
"data": [
  {
    "date": 1577836800000,
    "@NOTIFICATION_SENT": 62629,
    "@NOTIFICATION_OPENED": 404
},
{
   "date": 1577923200000,
   "@NOTIFICATION_OPENED": 734
  }
 ]
}

# use your create_json function
def create_json(id, notificationSent, notificationOpened):
return {(id):{
    'id': id,
    'notificationSent': notificationSent,
    'notificationOpened': notificationOpened,
    }}

# define an ID value (needed for the create_json function)
id = 0 

# initialise output dictionary
newJsonx = dict() 

# add items to the dictionary
for elem in statdata["data"]:
    for item in elem:
        try:
            notificationOpened = elem["@NOTIFICATION_OPENED"]
        except:
            notificationOpened = '0'
        print(notificationOpened)
        try:
            notificationSent = elem["@NOTIFICATION_SENT"]
        except:
            notificationSent = '0'
       newJson = create_json(id, notificationSent, notificationOpened)
       newJsonx.update(newJson)
       id =+ 1

这使得:

newJsonx
{0: {'id': 0, 'notificationSent': 62629, 'notificationOpened': 404}, 1: {'id': 1, 'notificationSent': '0', 'notificationOpened': 734}}

相关问题 更多 >