簡體   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