i73 i73 - 1 month ago 8
Python Question

Proper way to concatenate a tuple with keys and values (Python)

I have a tuple that is populated with elements from a directory:

{'C:/foo' : ['bar1', 'bar2'], 'C:/foo2' : ['bar']}


and I am trying to concatenate each key with its values:

C:/foo/bar1
C:/foo/bar2
C:/foo2/bar


I thought this would work:

[''.join('%s/%s' % (d.keys(), value)) for value in d.values()]


But it's just concatenating the key with the value in the same way as:

for k,v in d.items():
print(k'/'v)


Any help in this area would be greatly appreciated! If I am going at this the wrong way please tell me.

Thanks!

Answer

You can use os.path.join to build up paths in this manner.

import os
d = {'C:/foo' : ['bar1', 'bar2'], 'C:/foo2': ['bar']}
for k,v in d.items():
    for value in v:
        print(os.path.join(k,value))

Output

C:/foo2\bar
C:/foo\bar1
C:/foo\bar2

Then to make sure the slashes are all the correct way you can use os.path.normpath

for k,v in d.items():
    for value in v:
        print(os.path.normpath(os.path.join(k,value)))

Output

C:\foo2\bar
C:\foo\bar1
C:\foo\bar2

To be clear, you should prefer using os.path because it will robustly handle path manipulation in an operating system specific manner. In this case ensuring the correct number of slashes (including escaping if necessary), and which types of slashes (forward vs backward).

Comments