How to turn the for statement when there are multiple values for one key in the dictionary

What I wanted to do

Call the jinja2 template of / templates as shown below, and after rendering, place it under playbooks with the same configuration.


/User/taka
|--main.py
|--templates
|  |--inf
|  |  |--group_vars
|  |  |  |--test001.yml.j2
|  |  |  |--test002.yml.j2
|  |  |--inventory
|  |  |  |--inv_test001.yml.j2
|  |  |  |--inv_test002.yml.j2
|--playbooks
|  |--inf
|  |  |--group_vars
|  |  |  |--test001.yml.j2
|  |  |  |--test002.yml.j2
|  |  |--inventory
|  |  |  |--inv_test001.yml.j2
|  |  |  |--inv_test002.yml.j2

Points that struggled

How to turn the for statement when there are multiple values for one key in the dictionary

I tried to turn the for statement with a list type dictionary as shown below, but of course it is in key-value format, so the next value overwrites the previous value, and test002.yml.j2, inv_test002 is in the playbook directory. Only .yml.j2 was made

        self.j2_files = defaultdict(list)
        self.j2_files['group_vars'].append("test001.yml.j2")
        self.j2_files['group_vars'].append("test002.yml.j2")
        self.j2_files['inventory'].append("invt_est001.yml.j2")
        self.j2_files['inventory'].append("inv_test002.yml.j2")

        env = Environment(trim_blocks = True, loader =              
     FileSystemLoader(os.path.join("User", "taka", "templates", "inf"))

Even if I googled [multiple values for one key in Python dictionary] in English, I couldn't come up with a plan that I thought, so I got a little stuck.

The result was solved as follows

1        for k in self.j2_files.keys():
2            for v in self.j2_files[k]:
3                tmpl = env.get_template(k + "/" + v)
4                with open(os.path.join(User,taka,inf, k, v), "wb") as f:
5                    f.write(tmpl.render(self.test_conf).encode("utf-8"))

1: Store the key of j2_files, that is, group_vars and inventory in k 2: Store the value corresponding to the key of j2_files in v 3: Specify that the location of the template is fetched from the k + "/" + v directory under templates / inf 4: Specify the output destination 5: Generate a jinja file from the specified dictionary

Recommended Posts

How to turn the for statement when there are multiple values for one key in the dictionary
How to write a string when there are multiple lines in python
[python] How to check if the Key exists in the dictionary
How to define multiple variables in a python for statement
How to get all the keys and values in the dictionary
[Introduction to Python] How to use the in operator in a for statement?
Memorandum Regular expression When there are multiple characters in the character string that you want to separate
How to assign multiple values to the Matplotlib colorbar
Execution order when multiple context managers are specified in the Python with statement
Turn multiple lists with a for statement at the same time in Python
When you want to plt.save in a for statement
[Python] How to output the list values in order
[Jinja2] Solution to the problem that variables added in the for statement are not inherited
How to embed multiple embeds in one message with Discord.py
How to adapt multiple machine learning libraries in one shot
[Python] How to write an if statement in one sentence.
How to check if the contents of the dictionary are the same in Python by hash value
I didn't know how to use the [python] for statement
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
How to execute the sed command many times using the for statement
How to set the output resolution for each keyframe in Blender
How to handle multiple versions of CUDA in the same environment
Behavior when 0, 1, False, True is used for the dictionary (dict) key
How to get all the possible values in a regular expression
How to judge that the cross key is input in Python3
How to check the memory size of a dictionary in Python
How to convert 0.5 to 1056964608 in one shot
How to hide the command prompt when running python in visual studio 2015
How to check which is / dev / video ?? when multiple webcams are inserted
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
How to compare if the contents of the objects in scipy.sparse.csr_matrix are the same
Change the list in a for statement
How to handle consecutive values in MySQL
Python> set> Convert with set ()> dictionary is only key> I was taught how to convert the values of dictionary to set / dir ({}) / help ({}) / help ({} .values)
I want to visualize where and how many people are in the factory
How to take multiple arguments when doing parallel processing using multiprocessing in python
How to get the notebook name you are currently using in Google Colab
Tips for those who are wondering how to use is and == in Python
How to display in the entire window when setting the background image with tkinter
There are times when you can shorten the if statement using max · min
How to change the appearance of unselected Foreign Key fields in Django's ModelForm
[Python Tips] How to retrieve multiple keys with the maximum value from the dictionary
[Introduction to Python] How to get the index of data with a for statement
python> How to write multiple lines> How to write in mnist_with_summaries.py> It seems that there is no need for line concatenation symbols
How to use the C library in Python
How to specify the launch browser for JupyterLab 3.0.0
How to use MkDocs for the first time
Determining if there are birds in the image
How to write a ShellScript Bash for statement
How to get the files in the [Python] folder
Multiple graphs are displayed in one window (python)
How to find the correlation for categorical variables
Isn't there a default value in the dictionary?
How to store Python function in Value of dictionary (dict) and call function according to Key
How to list files under the specified directory in a list (multiple conditions / subdirectory search)
How to start the code written in Atom with one command without starting teminal
A memo when checking whether the specified key exists in the defined dictionary with python
How to check in Python if one of the elements of a list is in another list
Things to keep in mind when building automation tools for the manufacturing floor in Python
[Statistics for programmers] There is more than one way to calculate the average value