Issue
I have read several of the StackOverflow topics on this as well as Google. This is not my code. It was written for Python2. I am trying to understand a line that gives and error in Python 3. I am having difficulty wrapping my head around this one line for loop.
para['row_colors'] = pd.DataFrame([dict({'index': row}.items() + row_colors[row].items()) for row in table.index]).set_index('index')'
'row' is a sample name being used as a key. I get that. That '+' is throwing the error. Can't do a dict.item + dict.item. I don't understand the structure of the dictionary being built.
Solution
Yes, because dict.items()
no longer returns a list in Python 3, rather, it returns a special object that acts as a set-like view over the items in the dictionary (same with .keys
and .values
). The simplest fix is simply to do list(dict.items())
.
However, in this particular case, dict({'index': row}.items() + row_colors[row].items())
should probably just be {'index':row, **row_colors[row]}
in python 3.
So you could use:
para['row_colors'] = pd.DataFrame([{'index': row, **row_colors[row]} for row in table.index]).set_index('index')'
to use more modern syntax.
To understand what the previous version was doing, note that the dict
constructor accepts an iterable of key-value pairs:
>>> dict([('a', 1), ('b', 2)])
{'a': 1, 'b': 2}
Since .items()
used to return a list of key-value pairs, you could do something like
dict(d1.items() + d2.items())
To merge two dicts. To transliterate this into Python 3, you would need something like:
>>> d1 = {'foo': 'bar', 'baz': 'zing'}
>>> d2 = {"apple": 42}
>>> dict(list(d1.items()) + list(d2.items()))
{'foo': 'bar', 'baz': 'zing', 'apple': 42}
But python 3 has even more convenient syntax, you can just do:
>>> {**d1, **d2}
{'foo': 'bar', 'baz': 'zing', 'apple': 42}
Or, using specific key-value pairs more flexibly:
>>> {'index': 'column1', **d1, 'frob': 'bob', **d2}
{'index': 'column1', 'foo': 'bar', 'baz': 'zing', 'frob': 'bob', 'apple': 42}
Finally, note that Python 3.9 will be adding the |
operator as a merge operator for dicts, allowing the very terse:
>>> d1 | d2
{'foo': 'bar', 'baz': 'zing', 'apple': 42}
For the simplest case
Answered By - juanpa.arrivillaga
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.