gpt4 book ai didi

python - 如何使用计数器循环字典

转载 作者:行者123 更新时间:2023-12-01 00:42:30 24 4
gpt4 key购买 nike

所以我尝试使用 dict 进行排序循环。我想做的是,我的文件夹中有两个不同的 json 文件,我想在其中应用每个 dict对于每个 json 文件。意思是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 文件的第一个循环将是字典的第一个值,第二个循环将是字典的第二个值?

<小时/>

更新:

在我的文件夹中,我有两个 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 文件将具有来自 italian[0] 的第一个 webhook基本上。第二个 json 文件将包含第二个 webhook italian[1]。

我希望现在更清楚了! :)

最佳答案

counters 是一个 int ,而你的字典的键是字符串(并且大多数是任意的 AFAICT),所以显然这不能按预期工作。

如果你根本不关心排序(如果目录内容和 test 字典内容之间实际上没有真正的关系),你可以只使用字典的值作为列表:

test_list = list(test.values())
for i, fname in enumerate(os.listdir(...)):
print("i : {} - fname : {} - value : {}".format(i, fname, test_list[i]))

请注意,显然,如果目录中的条目多于字典中的条目,这将会崩溃。

如果订购很重要,那么您还有其他一些问题......

第一个是 Python 字典在 3.7.x 之前都是无序的,因此如果您想要一个适用于旧版 Python 版本的解决方案,您就不能使用普通字典 - 您需要一个 collections.OrderedDict 或者只是一个简单的 (key, value) 元组列表(您可以从中重建一个字典: vals = [("foo": "xxx"), ("bar: "yyy")]; test = dict(vals))

第二个问题是 os.listdir() 被明确记录为未排序(或者更准确地说,为“任意排序”,这意味着您不能依赖于排序)即使对于来自同一进程的同一路径上的两个连续调用也是如此),除了最终手动对列表进行排序之外,您无能为力。

长话短说:如果目录的内容和您的数据之间应该存在任何关系,您必须以某种方式自己明确地实现这种关系。

编辑:鉴于您更新的问题,正确的解决方案是以相反的方式解决问题:在python中配置url->文件名映射,并从此映射中读取文件,即:

# We're going to need this to solve possible path issues
# (relying on the current working directory is a recipe for headaches)
# NB: we assume the json files are in _HERE/slack/)
_HERE = os.path.dirname(os.path.abspath(__file__))

discordHooks = {
# list of `(url, filename)` pairs
'italian':[
('https://discordapp.com/api/webhooks/xxxxxxxxxxxxxx/qwertyuiop', 'jsonfile1.json'),
('https://discordapp.com/api/webhooks/xxxxxxxxxxxxxxxx/lkjahgfdsa' , 'jsonfile2.js')
]
}

for url, filename in discordHooks["italian"]:
path = os.path.join(_HERE, "slack", filename)
if not os.path.exists(path):
# Don't know how you want to handle the case...
raise ValueError("file {} not found".format(path))
print("url: {} - path: {}".format(url, path))

关于python - 如何使用计数器循环字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57253861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com