Reputation: 9718
I don't wan to use numpy to work with a 2D matrix
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.
But I'm having trouble figuring out how to get values from a row in the same order as I use my columns
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(<type 'dict'>, {
'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]
I want a list of values in the "original" order
[13, 28, 45, 42]
Is there a clean easy-to-read way of doing this?
@jamylak came with an answer that solved my specific problem.
But 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 __?
Upvotes: 0
Views: 2468
Reputation: 589
myDict = {'k42':'cat', 'k5':'fish', 'k1':'bird', 'k9':'dog'}
keyList = ['k1', 'k42', 'k9', 'k5']
outList = [myDict[x] for x in keyList]
Upvotes: 0
Reputation: 11543
clean and easy-to-read way would be using list comprehensions.
def readdict(D, rowkeys=(1, 2, 3)):
def readcol(d, columnKeys=('alfa', 'omega', 'bravo', 'charlie')):
return [d[key] for key in columnKeys]
return [readcol(D[key]) for key in rowkeys]
'''outputs :
[[13, 28, 45, 42],
[29, 19, 26, 42],
[13, 8, 4, 5]]'''
Upvotes: 3
Reputation: 7944
for row in dic.values(): #get each row 'dict'
for k,v in sorted(row.items(),key=lambda k: columnKeys.index(k[0])): #sort base on index of key occurring in columnKeys
print(k,v)
Would output for example:
('alfa', 43)
('omega', 30)
('bravo', 24)
('charlie', 2)
For {'omega': 29, 'charlie': 11, 'alfa': 4, 'bravo': 3}
Upvotes: 1
Reputation: 133764
from collections import defaultdict, OrderedDict
dic = defaultdict(OrderedDict)
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)
Upvotes: 7