Update dictionary if in list
<p>I'm running through an excel file reading line by line to create dictionaries and append them to a list, so I have a list like:</p>

<pre><code>myList = []
</code></pre>

<p>and a dictionary in this format:</p>

<pre><code>dictionary = {'name': 'John', 'code': 'code1', 'date': [123,456]}
</code></pre>

<p>so I do this: <code>myList.append(dictionary)</code>, so far so good. Now I'll go into the next line where I have a pretty similar dictionary:</p>

<pre><code>dictionary_two = {'name': 'John', 'code': 'code1', 'date': [789]}
</code></pre>

<p>I'd like to check if I already have a dictionary with <code>'name' = 'John'</code> in <code>myList</code> so I check it with this function:</p>

<pre><code>def checkGuy(dude_name):
  return any(d['name'] == dude_name for d in myList)
</code></pre>

<p>Currently I'm writing this function to add the guys to the list:</p>

<pre><code>def addGuy(row_info):
        if not checkGuy(row_info[1]):
            myList.append({'name':row_info[1],'code':row_info[0],'date':[row_info[2]]})
        else:
            #HELP HERE
</code></pre>

<p>in this else I'd like to <code>dict.update(updated_dict)</code> but I don't know how to get the dictionary here.</p>

<p>Could someone help so <code>dictionary</code> appends the values of <code>dictionary_two</code>?</p>

<p>If you <em>dict.update</em> the existing data each time you see a repeated name, your code can be reduced to a dict of dicts right where you read the file. Calling update on existing dicts with the same keys is going to overwrite the values leaving you with the last occurrence so even if you had multiple "John" dicts they would all contain the exact same data by the end.</p>

<pre><code>def read_file():
   results = {name: {"code": code, "date": date} 
                 for code, name, date in how_you_read_into_rows}
</code></pre>

<p>If you actually think that the values get appended somehow, you are wrong. If you wanted to do that you would need a very different approach. If you actually want to gather the dates and codes per user then use a <em>defauldict</em> appending the code,date pair to a list with the name as the key:</p>

<pre><code>from collections import defaultdict
d = defaultdict(list)
def read_file():
    for code, name, date in how_you_read_into_rows:
       d["name"].append([code, date])
</code></pre>

<p>Or some variation depending on what you want the final output to look like.</p>

python dictionary