In Python, given a dict (list or sequence) as in:
d={'a': 9, 'b': 6, 'c': 10],
I would like to create, in a clever way, the a directory structure like this:
'a_9/b_6/c_10'.
import os
def make_dir(dictionary):
for key, val in dictionary.items():
new_dir = f"{key}_{val}"
os.mkdir(new_dir)
os.chdir(new_dir)
EDIT: Or even more concise
import os
os.makedirs("/".join(f"{key}_{val}" for key, val in d.items()))
Dictionaries are not strictly ordered in Python (although as of Python 3.6
there is some level of order ), but if you sorted it (assuming you want that), perhaps by key, you could try something like follows:
new_dir = os.path.join(*[f'{k}_{v}' for k, v in sorted(d.items())])
os.makedirs(new_dir)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.