简体   繁体   中英

Dict python in loop Json gets just the last element

带按钮的 Bot 电报 Hi, i would like to create buttons on my telegram bot, which depend by the list '["Los Angeles","New York"]'. I have problem with the python dict, when i insert it in a loop, json gets just the last element (New York). Someone can explain me why?

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)

As mentioned by others in comments, it is strongly advised NOT to use a builtin name as a variable name (for example dict in the question code) as it can cause issues in other parts of code that depend on it. In the snippet below, I have used the name listb instead of dict .


I think what you want is this:

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

Explanation:

This line: dict = {"text": i} does not add a key to dict , it points dict variable to an entirely new dictionary and discards old value. So only the last value is retained.

In this particular case, the Telegram API expects a list of multiple dictionaries each with the key "text" in that place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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