0

In Python 3.6, I'm finding I'm unable to use the .join() method on two strings contained in a list, contained in a list, represented by a dictionary key when looping through the dictionary. To clarify, here's an example dictionary that represents the issue.

d = {0: [['abc', 'def'], 5, 'gjf'], 1: ['abc', 17, ['abc', 'def']], 2: [0, 1, 2]}

As you can see, all three keys have lists as values (as in my real dictionary). The first and second key also contain another list, which contain two strings. For some reason, I can't use .join() on them.

Here's my first attempt:

for key in d:
    for val in d[key]:
        if type(val) == list:
            val = ','.join(val)

There is no error message provided. When I run the above code and print d, the dictionary is exactly the same.

Additionally, I've attempted to assign the list to another variable and join the list there and reassign, but that failed as well. However, please bear in mind, this is all attempted in a loop (and for my purposes, I'm relatively certain it will have to be. The dictionary is fairly large, and the lists aren't in a definite position inside the dictionary).

There is no error message provided. When I run the above code and print d, the dictionary is exactly the same.

Another interesting occurrence is what happens when I run:

for key in d:
    for val in d[key]:
        print(val)

The output I get is: ['abc', 'def'] 5 gjf abc 17 ['abc', 'def'] 0 1 2

Rather than a grouping of three lists, which is what I expect. I do, however, get a grouping of three lists when I run the following:

for key in d:
    if type(d[key]) == list:
        print(d[key])

[['abc', 'def'], 5, 'gjf']
['abc', 17, ['abc', 'def']]
[0, 1, 2]

Am I doing something wrong? Is this built-in, and I'm simply unaware of a way around this? Is there a way around this?

Thanks for the help, and I apologize if this is too much (unnecessary) information.

SOLUTION:

for key in dd:
    i = 0
    for val in dd[key]:
        if type(val) == list:
            dd[key][i] = ','.join(val)
        i += 1

The above did what I was looking for, returning:

{0: ['abc,def', 5, 'gjf'], 1: ['abc', 17, 'abc,def'], 2: [0, 1, 2]}

Thanks for the help.

mwierda
  • 23
  • 2
  • 6
  • 3
    `join` has nothing to do with this. You're assigning to the loop variable. – user2357112 Jul 21 '17 at 16:15
  • 1
    You successfully used `.join()`, and assigned the results to the local variable `val` - and did nothing further with it. This does not magically cause some modification to your dictionary, simply because the previous value of `val` happened to have been retrieved from that dictionary. – jasonharper Jul 21 '17 at 16:18
  • You *never modified your dictionary*. – juanpa.arrivillaga Jul 21 '17 at 16:23
  • I understand, thanks for the help. I edited my question to contain the 'answer'. – mwierda Jul 21 '17 at 16:40

0 Answers0