簡體   English   中英

循環中的字典 python Json 僅獲取最后一個元素

[英]Dict python in loop Json gets just the last element

帶按鈕的 Bot 電報 嗨,我想在我的電報機器人上創建按鈕,這取決於列表 '["Los Angeles","New York"]'。 我對 python 字典有問題,當我將它插入循環時,json 只得到最后一個元素(紐約)。 有人可以解釋我為什么嗎?

import json
import time
from pprint import pprint
import telepot
from telepot.loop import MessageLoop
bot = telepot.Bot("token")
lista = ["Los Angeles","New York"]
for i in lista:
    dict = {"text": i}
    print(dict)
keyboard = {"keyboard": [[dict]]}


def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)

    if content_type == "text":
        bot.sendMessage(chat_id, msg["text"], reply_markup=keyboard)


MessageLoop(bot, handle).run_as_thread()
while 1:
    time.sleep(10)

正如其他人在評論中提到的那樣,強烈建議不要使用內置名稱作為變量名稱(例如問題代碼中的dict ),因為它可能會導致依賴它的代碼的其他部分出現問題。 在下面的代碼片段中,我使用了名稱listb而不是dict


我想你想要的是這樣的:

lista = ["Los Angeles","New York"]
listb = []
for i in lista:
    listb.append({"text": i})
    print(listb)
keyboard = {"keyboard": [listb]}

解釋:

這一行: dict = {"text": i}不向dict添加鍵,它將dict變量指向一個全新的字典並丟棄舊值。 所以只保留最后一個值。

在這種特殊情況下,Telegram API 需要一個包含多個字典的列表,每個字典在該位置都帶有鍵"text"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM