[英]How do I return all the desired dictionary values within an IF statement in python? (discord.py)
我正在嘗試遍歷此 JSON 字典中的所有值,以便在用戶將所需日期設置為生日時進行檢索。 但是,它只會返回第一個值。
這是我引用的字典:
{
"TARGETGUILD": {
"USERID1": {
"month": "09",
"day": "10"
},
"USERID2": {
"month": "09",
"day": "10"
}
},
"otherGUILD": {
"USERID": {
"month": "09",
"day": "10"
}
}
}
這是代碼:
@commands.command(name="today", pass_context=True)
async def today(self, ctx):
today = datetime.today()
today_month = today.strftime("%m")
today_day = today.strftime("%d")
guild_av = ctx.guild.icon_url
with open('commands/birthday/birthdays.json', 'r') as f:
data = json.load(f)
guild_data = data[str(ctx.guild.id)]
birthday_dict = {"month": str(today_month), "day": str(today_day)}
#length = len(guild_data)
def find_birthday():
for user in guild_data:
if guild_data[user] == birthday_dict:
return ":tada: <@!" + str(user) + ">" + "\n"
else:
return "`None`"
embed = discord.Embed(title=f":calendar_spiral: {today_month}/{today_day}", description="**Today's Birthdays:**" + "\n" + "\n" + str(find_birthday()), color=discord.Color.greyple())
embed.set_thumbnail(url=guild_av)
await ctx.send(embed=embed)
在此屏幕截圖中,您會看到它只會顯示第一個用戶。
例如,JSON 中的“其他”公會 ID 顯然可以正常工作,因為在此屏幕截圖中只有一個用戶的生日。
我已經嘗試了幾件事,只是想找出我的問題所在。
例如,當我這樣做時:
def find_birthday():
for user in guild_data:
print(user)
它確實打印每個用戶。 所以,這就是讓我相信這個問題在我的if
語句中的原因。 每當它看到用戶的生日匹配時,它只會打印第一個匹配的用戶。
所以,在瀏覽了很多線程之后......我只是不知道如何讓它列出每個人。
如果這是我缺少的簡單修復和/或簡單解決方案(通常總是如此),我深表歉意。 不過,我現在已經堅持了一段時間。 我還在學習 python。 如果有人能引導我朝着正確的方向前進,我將不勝感激。
問題
如何重寫它以允許它在
if
語句中返回多個值?
非常感謝。
return
語句退出循環。 它只是立即從 function find_birthday()
返回以將其結果返回給調用者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.