i’m working to create a keyboard on a telegram bot. I would like to create some buttons. I have a problem, i would to create create a sliding keyboard that goes down. There is a problem, with json you can create it by the code n1, but in python i cant find a solution. So how can i convert ‘lista = [“New York”,”Los Angeles”,”Miami”,”Toronto”,”Berlin”,”Rome”]’in json (code n1)?
#code n1 (JSON)
{"keyboard": [[{"text": "New York"}, {"text": "Los Angeles"}],
[{"text": "Miami"}, {"text": "Toronto"}],
[{"text": "Berlin"}, {"text": "Rome"}]]}
#code2
import json
import time
from pprint import pprint
import telepot
from telepot.loop import MessageLoop
bot = telepot.Bot("token")
lista = ["New York","Los Angeles","Miami","Toronto","Berlin","Rome"]
kdict = []
for i in lista:
kdict.append({"text": i})
print(kdict)
keyboard = {"keyboard": [kdict]}
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
Answers
To pair items in a list you can create an iterator from the list, zip the iterator with itself, and use a list comprehension to iterator through the zipped pairs:
This returns:
You can then convert it into JSON using
json.dumps
.Using blhsing answer