Writing from a dictionary to a text file in a sorted way (python)
<p>I have a code where i need to write a dictionary to a .txt file in order.</p>

<pre><code>with open("Items.txt", "w+") as file:
    for item in sorted(orders):
        file.write(item + "," + ",".join(map(str,orders[item])) + "\n")
        file.close      

        print("New stock level to file complete.")
</code></pre>

<p>Here orders is my dictionary which i want to write into Items.txt</p>

<p>Every time i run this i get a type error like this:</p>

<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>

<p>My contents of my dictionary are:</p>

<pre><code>orders[int(code)] = [str(name),int(current_stock),int(re_order),int(target_stock),float(price)]
</code></pre>

<p>Can some one please help me with this issue. I suspect that all the contents are not string but i don't know how to change the contents in the dictionary to a string.</p>

<p>PS: I cant change the contents in my dictionary to string as i need to use integer for later.</p>

<p>Because <code>item</code> will be an <code>int</code>, you cannot use the <code>+</code> operator with it on a string (<code>,</code>). Python is a strongly typed language. Use:</p>

<pre><code>file.write(str(item) + "," + ",".join(map(str,orders[item])) + "\n")
</code></pre>

<p>instead.</p>

python