Note that there are some explanatory texts on larger screens.

plurals
  1. POPython dict: get values sorted by a list of keys
    primarykey
    data
    text
    <p>I don't wan to use numpy to work with a 2D matrix</p> <p>I figured out how to create something that looks like a row and column dictionary. It works fine if I want to look up single values.</p> <p>But I'm having trouble figuring out how to get values from a row in the same order as I use my columns</p> <pre><code>from collections import defaultdict dic = defaultdict(dict) rowKeys = ['1','2','3'] columnKeys = ['alfa', 'omega', 'bravo', 'charlie'] # Filling up the dictionary with values from random import randrange for rKey in rowKeys: for cKey in columnKeys: dic[rKey][cKey] = randrange(50) """ print dic defaultdict(&lt;type 'dict'&gt;, { '1': {'omega': 28, 'charlie': 42, 'alfa': 13, 'bravo': 45}, '3': {'omega': 8, 'charlie': 5, 'alfa': 13, 'bravo': 4}, '2': {'omega': 19, 'charlie': 42, 'alfa': 29, 'bravo': 26}}) """ # print dic[rowKeys[0]].keys() # ['omega', 'charlie', 'alfa', 'bravo'] # In [28]: print dic[rowKeys[0]].values() # [28, 42, 13, 45] </code></pre> <p>I want a list of values in the "original" order</p> <pre><code>[13, 28, 45, 42] </code></pre> <p>Is there a clean easy-to-read way of doing this?</p> <hr> <h2>UPDATE</h2> <p>@jamylak came with an answer that solved my specific problem.</p> <p><strong>But</strong> it did not truly answer my question of how to get values by a list. Suppose I change the order of columnKeys alphabetically (or by other non-logic order) and want to get at list of values returned in that order. How would I go about that <em>_</em>_?</p>
    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.
 

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