Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This will add terms until <code>dic</code> does not contain <code>key</code>.</p> <pre><code>dic = {'had': ['a', 'little'], 'Mary': ['had', 'a'], 'a': ['little', 'lamb.']} key = 'Mary' res = [] while True: try: res.extend(dic[key]) key = dic[key][-1] except KeyError: break print ' '.join(res) </code></pre> <p>This yields:</p> <pre><code>['had', 'a', 'little', 'lamb.'] </code></pre> <p>Be aware: You will enter an infinite loop if all values also are a key. You will also encounter this if there is a repeating sequence in your dictionary, such as </p> <pre><code>{'a': ['b', 'c'], 'b': ['a', 'c'], 'c': ['a', 'b'], 'foo': ['bar', 'foobar']} </code></pre> <p>To avoid this, you could do one out of two things:</p> <ol> <li>Set a maximum iteration value</li> <li>Stop the iteration when you encounter a key that previously have been seen.</li> </ol> <p><strong>Maximum iteration value:</strong></p> <pre><code>dic = {'had': ['a', 'little'], 'Mary': ['had', 'a'], 'a': ['little', 'lamb.']} key = 'Mary' res = [] max_iterations = 10 i = 0 while i &lt; max_iterations try: res.extend(dic[key]) key = dic[key][-1] except KeyError: break i += 1 if i &gt; max_iterations: break print ' '.join(res) </code></pre> <p><strong>Stop at previously seen key</strong></p> <pre><code>dic = {'had': ['a', 'little'], 'Mary': ['had', 'a'], 'a': ['little', 'lamb.']} key = 'Mary' res = [] seen_keys = [] while True: if key in seen_keys: break try: res.extend(dic[key]) seen_keys.append(key) key = dic[key][-1] except KeyError: break print ' '.join(res) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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