0

Bot telegram with buttonsHi, 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)
2
  • Keys in a Python dictionary (or any key/value data structure in any language) are unique, so every time you map a value to a key it gets mutated. Is that what you are asking? Commented Apr 17, 2020 at 18:42
  • Strongly advise against using ‘dict’ as a variable name as this will override the builtin. Commented Apr 17, 2020 at 18:54

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I would strongly recommend not to use dict as a variable name for a list.
@NomadMonad Fixed(1). (I guess my comment saying this was deleted by somebody?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.