0

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'.
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
Waliston
  • 17
  • 1
  • 3
  • Hello @Waliston. What have you tried so far? – mrhd Dec 03 '19 at 14:41
  • Hi, i didn't yet. I would make a for loop on dict.keys() and for each iteration create the subdirectory, store it as a string variable in order to create next subdirectory on next for loop iteration. I am aiming to learn a new way for learning purpose. – Waliston Dec 03 '19 at 15:32

2 Answers2

0
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()))
Maciej B. Nowak
  • 1,180
  • 7
  • 19
0

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)
PyPingu
  • 1,697
  • 1
  • 8
  • 21
  • Thanks @PyPingu . I didn't realize the new interesting feature: OrderedDict on collections. Actually I want to sort dict keys according to some previously chosen separate list with human sorted keys. – Waliston Dec 03 '19 at 15:40
  • python 3.7.3 complains when issuing 'new_dir = ...' ------------- TypeError: expected str, bytes or os.PathLike object, not generator ------------ Can it be solved? I also have tried str(v) instead of v. @DavidGildour solution worked here. – Waliston Dec 03 '19 at 16:44
  • Yeah sorry I missed out the unpacking `*` – PyPingu Dec 03 '19 at 16:48
  • Interesting. Thanks. – Waliston Dec 03 '19 at 16:52