[英]How to switch the nesting structure of a dictionary of dictionaries in Python
[英]Nesting dictionary of dictionaries
我正在尝试嵌套两个字典,也许只制作一个字典更容易,但是,我有具有不同值的相同键,只是更改键更容易还是有办法嵌套这两个?
Number_As = 1
#DNA dictionary
DNAdict = {
'A': ['dAMP',1,..., other values],
'C': ['dCMP',2,..., other values],
'T': ['dTMP',3,..., other values],
'G': ['dGMP',4,..., other values]}
#RNA dictionary
RNAdict = {
'A': ['AMP',5,..., other values],
'C': ['CMP',6,..., other values],
'U': ['UMP',7,..., other values],
'G': ['GMP',8,..., other values]}
然后我尝试访问不同计算的各个值:
Energy of DNA_A = Number_As * DNAdict['A'][1]
Energy of DNA_A = 1
or
Energy of RNA_A = Number_As * RNAdict['A'][1]
Energy of RNA_A = 5
但我只想拥有一本字典,然后尽管名称相同,但仍可以访问每个键的不同值。 是否可以?
非常感谢!!
你怎么知道你现在想使用哪个字典? 如果您想在当前状态下对 dict 的各个元素保持很少的控制(例如, ['dAMP',1,..., other values]
,您可以将 dict 的值设为列表列表并参考通过索引到所需元素。但是,如果您可以为每个元素分配一个唯一名称,则确实可以使用以下代码创建嵌套字典:
# Your current code goes here
acids = {'DNA': RNAdict, 'DNA': DNAdict}
# Then you can access a specific dict by
dna_a_energy = Number_As * acids['DNA']['A'][1]
rna_a_energy = Number_As * acids['RNA']['A'][1]
如果我理解正确的话。
是的,所有的可能性,它都有可能
1:硬编码:
grouped = {
'DNAdict':{
'A': ['dAMP',1,..., ],
'C': ['dCMP',2,..., ],
'T': ['dTMP',3,..., ],
'G': ['dGMP',4,..., ]},
'RNAdict':{
'A': ['AMP',5,..., ],
'C': ['CMP',6,..., ],
'U': ['UMP',7,..., ],
'G': ['GMP',8,..., ]}
}
#acessing RNAdict a[0]
value = grouped['RNAdict']['A'][0]
print(value)
2:按代码分组
#RNA dictionary
DNAdict = {
'A': ['dAMP',1,..., ],
'C': ['dCMP',2,..., ],
'T': ['dTMP',3,..., ],
'G': ['dGMP',4,..., ]}
#RNA dictionary
RNAdict = {
'A': ['AMP',5,..., ],
'C': ['CMP',6,..., ],
'U': ['UMP',7,..., ],
'G': ['GMP',8,..., ]}
grouped = {'DNAdict':DNAdict,'RNAdict':RNAdict}
#example of finding
value = grouped['RNAdict']['A'][0]
print(value)
3 添加前缀:
def add_prefix(elem:dict,prefix:str)->dict:
new_dict = {}
for key in elem.keys():
new_dict[f'{prefix}_{key}'] = elem[key]
return new_dict
DNAdict = {
'A': ['dAMP',1,..., ],
'C': ['dCMP',2,..., ],
'T': ['dTMP',3,..., ],
'G': ['dGMP',4,..., ]}
#RNA dictionary
RNAdict = {
'A': ['AMP',5,..., ],
'C': ['CMP',6,..., ],
'U': ['UMP',7,..., ],
'G': ['GMP',8,..., ]}
Dna = add_prefix(elem=DNAdict,prefix='DNA')
Rna = add_prefix(elem=RNAdict,prefix='RNA')
Nested= {**Dna, **Rna}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.