Accessing dictionary keys&values via list of keys and values
<p>This is going to be a very embarrassing first post from me - just coming back to coding in Python after learning basics ~6 months ago and not using it since then.</p>

<p>I am coding a Blackjack game in object oriented approach, and defined a Deck object as shown below:</p>

<pre><code>class Deck(object):
    suits = ["spades", "clubs", "diamonds", "hearts"]
    ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]

def __init__(self):
    self.spades = {"2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "7": 0, "8": 0, "9": 0, "10": 0, "Jack": 0, "Queen": 0, "King": 0, "Ace": 0}
    self.clubs = {"2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "7": 0, "8": 0, "9": 0, "10": 0, "Jack": 0, "Queen": 0, "King": 0, "Ace": 0}
    self.diamonds = {"2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "7": 0, "8": 0, "9": 0, "10": 0, "Jack": 0, "Queen": 0, "King": 0, "Ace": 0}
    self.hearts = {"2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "7": 0, "8": 0, "9": 0, "10": 0, "Jack": 0, "Queen": 0, "King": 0, "Ace": 0}
</code></pre>

<p>Afterwards, I wanted to create a neat method which would initiate this deck by filling all 4 dictionaries holding count of ranks in each suit, by writing something like below (that's the reason for class attributes I defined above:</p>

<pre><code>def initialize_deck(self):
    for suit in self.suits:
        for rank in self.ranks:
            self.suit[rank] = 1
</code></pre>

<p>The problem is, the code just does not do what I think it should be doing (as in e.g.: pulling first suit from self.suits list, using it as a name of the dictionary iterating over all its keys and setting their associated values to 1). Instead I just get an error "AttributeError: 'Deck' object has no attribute 'suit'".</p>

<p>What am I doing wrong in here? Is there a neat way of writing what I have in mind with 2 nested loops, instead of writing it like below?</p>

<pre><code>def initialize_deck(self):
    for rank in self.ranks:
        self.spades[rank] = 1
    for rank in self.ranks:
        self.clubs[rank] = 1
    for rank in self.ranks:
        self.diamonds[rank] = 1
    for rank in self.ranks:
        self.hearts[rank] = 1
</code></pre>

<p>Thanks in advance for answers to what I know is probably a very basic problem.</p>

<p>Cheers</p>

<p>You can use <code>getattr</code> function do get attribute from object</p>

<pre><code>def initialize_deck(self):
    for suit in self.suits:
        suit_dict = getattr(self, suit)
        for rank in self.ranks:
            suit_dict[rank] = 1
</code></pre>

<p>Or you can do it using <code>setattr</code></p>

<pre><code>def initialize_deck(self):
    rank_map = {key: 1 for key in self.ranks}
    for suit in self.suits:
        setattr(self, suit, rank_map.copy())
</code></pre>

python dictionary iteration