Greetings,<br><br>I'm trying to categorize items in a list, by copying them into a dictionary...<br>A simple example with strings doesn't seem to work how I'd expect:<br><br><span style="font-family: courier new,monospace;">>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']</span><br style="font-family: courier new,monospace;">
<span style="font-family: courier new,monospace;">>>> d = {}</span><br style="font-family: courier new,monospace;"><span style="font-family: courier new,monospace;">>>> d = d.fromkeys(basket, [])</span><br style="font-family: courier new,monospace;">
<span style="font-family: courier new,monospace;">>>> d</span><br style="font-family: courier new,monospace;"><span style="font-family: courier new,monospace;">{'orange': [], 'pear': [], 'apple': [], 'banana': []}</span><br style="font-family: courier new,monospace;">
<span style="font-family: courier new,monospace;">>>> for fruit in basket:</span><br style="font-family: courier new,monospace;"><span style="font-family: courier new,monospace;">...     d[fruit].append(fruit)</span><br style="font-family: courier new,monospace;">
<span style="font-family: courier new,monospace;">... </span><br style="font-family: courier new,monospace;"><br>No if I print d I'd EXPECT....<br><span style="font-family: courier new,monospace;">>>> d</span><br style="font-family: courier new,monospace;">
<span style="font-family: courier new,monospace;">
{'orange': ['orange', 'orange'],
'pear': ['pear'],
'apple': ['apple', 'apple'],
'banana': ['banana']}</span><br style="font-family: courier new,monospace;">
<br>But what I GET is....<br><span style="font-family: courier new,monospace;">>>> d</span><br style="font-family: courier new,monospace;"><span style="font-family: courier new,monospace;">{'orange': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'pear': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'apple': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'banana': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']}</span><br style="font-family: courier new,monospace;">
<span style="font-family: courier new,monospace;">>>> </span><br style="font-family: courier new,monospace;"><br>From what I can work out, there is only ONE list that is referenced from the dictionary 4 times. Which would be because the <i>same empty list</i> is assigned to every key in the dictionary by the "fromkeys" line. But that seems <i>seriously </i>counter-intuitive to me...<br>
<br>Would anyone beg to differ and try to rewire my thinking? (I'm from a Java background if that helps)<br><br>I've already solved the problem a different way, but I am concerned about this counter-intuitiveness as I see it.<br>
<br>rgds,<br>Daniel Jowett<br>