Reputation: 629
So I am trying to make a sort loop using dict
. What I am trying to do is that I have two different json files in my folder where I want to apply each dict
for each json file. Meaning the json
file 1 would be the first in dict and the second json file would the second 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]))
My idea here is that I want it to loop through each json file using for counters, file in enumerate(os.listdir(directory)):
and what I want it to happend is that the first loop would be the first json file == should print out the first dict value and the next loop would be second dict value.
However I do not know how to do it and I do not want to use lists either.
How am I able to loop through each dict so the first loop of json file would be first value of dict and the second loop would be the second value of dict?
Update:
In my folder I have two json files where the first one is called Thrill.json
and second file is HelloWorld.json
and those are always the same (There wont be added new json files or removed json at any time).
So for now I am using the code:
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]))
so basically what I am trying to do is that I want the first json Thrill
to print out the first value in the list which is https://discordapp.com/api/webhooks/xxxxxxxxxxxxxx/qwertyuiop
and when the that is done we go through the second loop which is going to print out https://discordapp.com/api/webhooks/xxxxxxxxxxxxxxxx/lkjahgfdsa
And thats pretty much it, There is values inside the json files that I will apply later in the code (Nothing I have coded yet) but it is important that the first json file will have the first webhook from italian[0] basically. and the second json file will have the second webhook italian[1].
I hope this is more clear now! :)
Upvotes: 1
Views: 127
Reputation: 45762
from pathlib import Path
def make_language_dict(thrill_hook: str, helloworld_hook: str):
return {
"Thrill": thrill_hook
"HelloWorld": helloworld_hook
}
discord_hooks = {
'swedish': make_language_dict(
thrill_hook='https://discordapp.com/api/webhooks/xxxxxxxxxxxxxx/ASDFDFGDSFGSDFG',
helloworld_hook='https://discordapp.com/api/webhooks/xxxxxxxxxxxxxxxx/EAAEFAEFAFlF'
),
'italian':make_language_dict(
thrill_hook='https://discordapp.com/api/webhooks/xxxxxxxxxxxxxx/qwertyuiop',
helloworld_hook='https://discordapp.com/api/webhooks/xxxxxxxxxxxxxxxx/lkjahgfdsa'
),
}
def send_to_discord(directory: Path = Path(r"./slack")):
for filepath in directory.glob("*.json"):
with open(filepath.resolve()) as slack_attachment:
for language in discord_hooks:
discord_hook = discord_hooks[language][filepath.stem]
print(discord_hook)
# Do stuff with the file and the discord_hook here...
Upvotes: 0
Reputation: 77952
counters
is an int and your dict's keys are strings (and mostly arbitrary ones AFAICT) so obviously this cannot work as expected.
If you don't care at all about ordering (if there's actually no real relationship between the directory content and the test
dict content), you can just use the dict's values as a list:
test_list = list(test.values())
for i, fname in enumerate(os.listdir(...)):
print("i : {} - fname : {} - value : {}".format(i, fname, test_list[i]))
Just note that this will crash if you have more entries in your directory than you have in your dict, obviously.
If ordering matters, then you have a couple other issues...
The first one is that Python dicts are unordered until 3.7.x so if you want a solution that does work with older Python versions you just cannot use a plain dict - you need either a collections.OrderedDict
or just a plain list of (key, value)
tuples (from which you can rebuild a dict: vals = [("foo": "xxx"), ("bar: "yyy")]; test = dict(vals)
)
The second issue is that os.listdir()
is specifically documented as not being ordered either (or, more exactly, as being "arbitrary ordered", which means you cannot rely on the ordering being the same even for two consecutive calls on the same path from the same process), and here there's not much you can do except eventually sorting the list manually.
To make a long story short: if there's supposed to be any relationship between the directory's content and your data, you do have to explicitely implement this relationship yourself one way or another.
EDIT: given your updated question, the proper solution would be to take the issue the other way round: configure the url->filename mapping in python, and read the files from this mapping, ie:
# 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))
Upvotes: 2