Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>One good place to start is by getting iPython (<code>easy_install ipython</code>) then poking around with tab completion, <code>?</code> and <code>dir</code>:</p> <pre><code>In [2]: dir {} ------&gt; dir({}) Out[2]: ['__class__', ... 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] In [3]: {}.update? Type: dict Base Class: &lt;type 'dict'&gt; String Form: {} Namespace: Interactive Length: 0 Docstring: dict() -&gt; new empty dictionary. dict(mapping) -&gt; new dictionary initialized from a mapping object's (key, value) pairs. dict(seq) -&gt; new dictionary initialized as if via: d = {} for k, v in seq: d[k] = v dict(**kwargs) -&gt; new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) </code></pre> <p>(just for example)</p> <p>Anyway, your problem with checking keys common between the two dictionaries: there are a few things to consider (maybe look at the <code>set</code> class?), but here's how I'd do it:</p> <pre><code>common_keys = [k for k in dict1 if k in dict2] </code></pre> <p>(ie, "each key <code>k</code> in dict1 if that key is also in dict2") (note, too, that testing for dictionary membership is an O(1) operation, so this will run in O(|dict1|))</p> <p><strong>edit</strong>: alright, so this doesn't solve the problem of merging the two dicts into one with lists... But Lott's answer is good for that, or you could use the <code>setdefault</code> method:</p> <pre><code>new = {} for (k, v) in dict1.items(): new.setdefault(k, []).append(v) for (k, v) in dict2.items(): new.setdefault(k, []).append(v) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload