繁体   English   中英

使用Python将项目添加到列表

[英]Add an item to the list with 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

谢谢。

hello是字典,而不是列表。

无论使用

hello = []

要么

hello[x] = "something"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM