【发布时间】:2019-07-29 12:25:48
【问题描述】:
所以我正在尝试使用dict 进行排序循环。我想要做的是我的文件夹中有两个不同的 json 文件,我想为每个 json 文件应用每个 dict。这意味着json 文件 1 将是 dict 中的第一个,第二个 json 文件将是第二个 dict。
discordHooks = {'swedish': [
'https://discordapp.com/api/webhooks/xxxxxxxxxxxxxx/ASDFDFGDSFGSDFG',
'https://discordapp.com/api/webhooks/xxxxxxxxxxxxxxxx/EAAEFAEFAFlF'],
'italian':[
'https://discordapp.com/api/webhooks/xxxxxxxxxxxxxx/qwertyuiop',
'https://discordapp.com/api/webhooks/xxxxxxxxxxxxxxxx/lkjahgfdsa']
}
def sendToDiscord():
directory = os.fsencode('./slack')
for counters, file in enumerate(os.listdir(directory)):
filename = os.fsdecode(file)
if filename.endswith(".json"):
with open('./slack/' + filename) as slackAttachment:
print(discordHooks.get('italian', [counters]))
我的想法是我希望它使用for counters, file in enumerate(os.listdir(directory)): 循环遍历每个 json 文件,我希望它发生的是第一个循环将是第一个 json 文件 == 应该打印出第一个 dict 值和下一个循环将是第二个字典值。
但是我不知道该怎么做,我也不想使用列表。
我如何能够遍历每个 dict 以便 json 文件的第一个循环将是 dict 的第一个值,而第二个循环将是 dict 的第二个值?
更新:
在我的文件夹中,我有两个 json 文件,第一个名为 Thrill.json,第二个文件是 HelloWorld.json,它们始终相同(不会随时添加新的 json 文件或删除 json)。
所以现在我正在使用代码:
discordHooks = {'swedish': [
'https://discordapp.com/api/webhooks/xxxxxxxxxxxxxx/ASDFDFGDSFGSDFG',
'https://discordapp.com/api/webhooks/xxxxxxxxxxxxxxxx/EAAEFAEFAFlF'],
'italian':[
'https://discordapp.com/api/webhooks/xxxxxxxxxxxxxx/qwertyuiop' #This going tobe applied for the first json,
'https://discordapp.com/api/webhooks/xxxxxxxxxxxxxxxx/lkjahgfdsa' #this going to applied to second json]
}
def sendToDiscord():
directory = os.fsencode('./slack')
for counters, file in enumerate(os.listdir(directory)):
filename = os.fsdecode(file)
if filename.endswith(".json"):
with open('./slack/' + filename) as slackAttachment:
print(discordHooks.get('italian', [counters]))
所以基本上我想要做的是我希望第一个 json Thrill 打印出列表中的第一个值 https://discordapp.com/api/webhooks/xxxxxxxxxxxxxx/qwertyuiop ,当完成后,我们将通过第二个循环打印出https://discordapp.com/api/webhooks/xxxxxxxxxxxxxxxx/lkjahgfdsa
差不多就是这样,json 文件中有一些值,我稍后将在代码中应用(我还没有编写任何代码),但重要的是第一个 json 文件将具有来自意大利的第一个 webhook[0]基本上。第二个 json 文件将有第二个 webhook italian[1]。
我希望现在更清楚了! :)
【问题讨论】:
-
列出列表中的所有文件路径,然后使用 with open 读取文件并使用 json.load 将该 dict 文件添加到您的 dic
-
将字典的键设为文件名,不要使用枚举,即将
'Hello'替换为"file_1.json" -
@Dan 我不太明白我将如何完成它,如果你能做一个简单的代码示例,是否有可能?
-
@Thrillofit86 当然,添加了答案
-
但是
swedish...呢?
标签: python dictionary for-loop