Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python数组中插入JSON_Python_Json_Dictionary - Fatal编程技术网

在Python数组中插入JSON

在Python数组中插入JSON,python,json,dictionary,Python,Json,Dictionary,我在Python的for循环中创建了一个dict,dict={year:{month:{day:{title]}},其中year,month,day和title都是变量。然后我使用了data=json.dumps(dict),这非常有效。但是,如果日期相同,我希望它向数组中添加另一个[title]方面,因此 for title in x: dict = {year:{month:{day:[title]}}} data = json.dumps(dict) if day==day

我在Python的for循环中创建了一个
dict
dict={year:{month:{day:{title]}}
,其中
year
month
day
title
都是变量。然后我使用了
data=json.dumps(dict)
,这非常有效。但是,如果日期相同,我希望它向数组中添加另一个
[title]
方面,因此

for title in x:
    dict = {year:{month:{day:[title]}}}
    data = json.dumps(dict)
if day==day:
    //insert another [title] right next to [title]
我尝试过使用
append
update
insert
,但都不起作用

我该怎么做呢?

注意,如前所述,您正在创建一个Python
dict
——而不是一个Python
列表(也称为JSON“数组”)。因此,当你说“[title]紧挨着[title]”时,会有一点混乱。dict不使用您期望的顺序(它们使用散列顺序)

将JSON转储到字符串后,您试图添加一个字段。你应该在扔掉它之前就这么做。更重要的是,您在每个循环中都丢弃了
dict
数据
变量。正如所写的,您的代码将只能访问循环最后一次迭代中的变量

还有一个重要的提示:不要超载
dict
。将变量重命名为其他变量

另外,您的行
day==day
将始终返回
True

以下是我认为您正在尝试做的事情:您正在创建一个“日历”,它按年、月、日进行组织。每天都有一个“标题”列表


那不是数组。这是一个dict。即使在JSON术语中,它也是一个对象,而不是数组。然后在转储它之前检查并添加
[title]
?正如@user2357112所说,您不是在制作Python列表(JSON数组),而是在制作dict(JSON对象)。@CaseyFalk这很有意义,但我如何添加它?以及“标题旁边的标题”是什么意思/@用户3822146,“添加”是什么意思?你想得到什么结果?
# Variables I'm assuming exist:
# `title`, `year`, `month`, `day`, `someOtherDay`, `titles`, `someOtherTitle`

myDict = {}
for title in titles: #Renamed `x` to `titles` for clarity.
    # Make sure myDict has the necessary keys.
    if not myDict[year]:
        myDict[year] = {}
    if not myDict[year][month]: 
        myDict[year][month] = {}

    # Set the day to be a list with a single `title` (and possibly two).
    myDict[year][month][day] = [title]
    if day==someOtherDay:
        myDict[year][month][day].append(someotherTitle)

    # And FINALLY dump the result to a string.
    data = json.dumps(myDict)