Reputation: 1749
I have 3 variables, a,b and c, and 3 coefficients a_b, a_c and b_c. I want to use these to build a nested dictionary rels that would be the following:
a b c
a 1 a_b a_c
b a_b 1 b_c
c a_c b_c 1
So for example:
rels['a']['b']=a_b
rels['b']['c']=b_c
rels['a']['a']=1
and so on
Clearly, I can make this by hardcoding:
rels = {}
rels['a']={{'a':1,'b':a_b,'c':a_c}}
and so on. I was wondering if there was a more elegant/efficient way of doing this?
Upvotes: 0
Views: 55
Reputation: 379
You can iterate over your list and for every item item in list you can find the relation of that item(or each variable) with all the variables in the list and store them in another list In Simple Way - `
var = ['a','b','c']
rels = {}
for item in var:
rel = {}
for i in range(0,len(var)):
if(item == var[i]):
rel[item] = 1
else:
rel[item] = item+"_"+var[i]
rels[item] = rel
Upvotes: 1
Reputation: 71461
You can split the data and use a dictionary comprehension:
import re
s = """
a b c
a 1 a_b a_c
b a_b 1 b_c
c a_c b_c 1
"""
new_s = [list(filter(None, re.split('\s+', i))) for i in filter(None, s.split('\n'))]
new_data = {a:dict(zip(new_s[0], b)) for a, *b in new_s[1:]}
Output:
{'a': {'a': '1', 'b': 'a_b', 'c': 'a_c'}, 'b': {'a': 'a_b', 'b': '1', 'c': 'b_c'}, 'c': {'a': 'a_c', 'b': 'b_c', 'c': '1'}}
Upvotes: 2