Pedro Klain
Pedro Klain

Reputation: 3

Why are the keys of a dictionary going inside the items?

I have a problem that it seems to me that it doesn't make sense. I am defining a dictionary and using it to generate a list, with keys as the first elements of the list. But when I run it, not only the list is created, but the dictionary is modified. I need to know why this is happening and in which other way I could do this list without modifying the dictionary. A generical code example is the following:


class report:
    def __init__(self):
        self.dict_content= self.get_dict()
        self.labels = self.get_labels()

    def get_dict(self):

        dict_content = dict(A1 = ['a', 'b', 'c'], A2 = ['d', 'e', 'f'])

        return dict_content

    def get_labels(self):
        
        labels = []
        
        for item in self.dict_content.items():
            new_items = item[1]
            new_items.insert(0, item[0])
            labels.append(new_items)
            
        return labels

Calling in the console,

r = report()

labels = r.labels
print(labels)
[['A1', 'a', 'b', 'c'], ['A2', 'd', 'e', 'f']]

dict_content = r.dict_content
print(dict_content)
{'A1': ['A1', 'a', 'b', 'c'], 'A2': ['A2', 'd', 'e', 'f']}

If I comment the line self.labels = self.get_labels() and do the last operations, I get:

r = report()
dict_content = r.dict_content
print(dict_content)
{'A1': ['a', 'b', 'c'], 'A2': ['d', 'e', 'f']}

And what I expect it to be is:

r = report()

labels = r.labels
print(labels)
[['A1', 'a', 'b', 'c'], ['A2', 'd', 'e', 'f']]

dict_content = r.dict_content
print(dict_content)
{'A1': ['a', 'b', 'c'], 'A2': ['d', 'e', 'f']}

What is happening?

Upvotes: 0

Views: 36

Answers (1)

mkrieger1
mkrieger1

Reputation: 23235

for item in self.dict_content.items():
    new_items = item[1]
    new_items.insert(0, item[0])
    labels.append(new_items)

Here, new_items, despite its name, is not a new list, but a reference to the original list contained in dict_content.

By using its insert method, you modify this list, which is reflected when looking at dict_content later.

Instead of modifying the original list, you want to create a new list. For example, by concatenation:

for item in self.dict_content.items():
    new_items = [item[0]] + item[1]
    labels.append(new_items)

Upvotes: 2

Related Questions