Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.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向列表中添加一项_Python - Fatal编程技术网

使用Python向列表中添加一项

使用Python向列表中添加一项,python,Python,我试图使用.append()将新项目添加到列表中,但无法处理我的问题 我想在列表中插入如下数据: hello = {} 为什么会这样?我用代码解释了它 hello = {} # I don't want to use with hello : [] # Because I'll use it to write into file like this : {u'list1': {'hello1': {}, 'hello2': {}}, u'list2': {'hello3': {}, 'hell

我试图使用.append()将新项目添加到列表中,但无法处理我的问题 我想在列表中插入如下数据:

hello = {}
为什么会这样?我用代码解释了它

hello = {} # I don't want to use with hello : []
# Because I'll use it to write into file like this : {u'list1': {'hello1': {}, 'hello2': {}}, u'list2': {'hello3': {}, 'hello4': {}}}

GoodWords = ["hello1", "hello2"]

def Write(filename, data):
    fp = file(filename, 'w')
    fp.write(data)
    fp.close()

"""
Here why I would like to use {} not []
It'll be write like this : {u'list1': {'hello1': {}, 'hello2': {}}}

def start():
    if not "list1" in hello:
        hello["list1"] = {}
    for x in GoodWords:
        hello["list1"][x] = {}
    Write("test.txt", str(hello))


"""

def start():
    # Any idea to use .append() with {} or something like
    for x in GoodWords:
        hello.append(x)

try: start(); sleep(4)
except Exception as why: print why

谢谢。

这是一本字典,不是列表

任用

hello=[]


hello[x]=“something”

hello={}是一个字典,但不是一个列表。@m170897017啊哈,意思是我不能添加新项目?如果你想向字典添加新项目,只需字典['new_key']=“new_value.”“新值”可以是您喜欢的任何类型的对象。@m170897017 aha谢谢