使用Python将项添加到列表中

时间:2015-03-26 06:23:58

标签: 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': {}, '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

感谢。

1 个答案:

答案 0 :(得分:2)

hello是字典,而不是列表。

使用

hello = []

hello[x] = "something"