Christian.T
Christian.T

Reputation: 17

Why are all dictionary key values being updated instead of just the one I am specifying?

I have a dictionary with dates as key names:

dateDict = dict.fromkeys(newDateRange,[])

Out:

{'2021-02-09': [], '2021-02-08': []}

I also have the following class:

class attendance:
    def matchDate(self):
        if self.datein date_dict:
        date_dict[self.date].extend(self.names)
            
    def __init__(self, names, date):
        self.tickers = names
        self.date= date

My idea is to have an object with the same format in self.date as a key name in dateDict. For example, self.date would be '2021-02-09', and somewhere in dateDic is a key also called '2021-02-09'. However, whenever I run my code, the object updates both keys with its values instead of the one I am trying to specify.

In:

whosHere = attendance(['Billy','Kyle','Joe','Ashley'], '2021-02-09')
whosHere.matchDate()

dateDict

Out:

{'2021-02-09': ['Billy','Kyle','Joe','Ashley'], '2021-02-08': ['Billy','Kyle','Joe','Ashley']}

Instead of just:

{'2021-02-09': ['Billy','Kyle','Joe','Ashley'], '2021-02-08': []}

Upvotes: 0

Views: 115

Answers (1)

Barmar
Barmar

Reputation: 780724

dict.from_keys() is using the same list as the value of all the keys.

Use a dictionary comprehension instead.

dateDict = {key: [] for key in newDateRange}

Upvotes: 2

Related Questions