python命令字典重复键 [英] python ordered dict with duplicates keys
问题描述
我正在尝试编写一些python函数来生成一批输入文件,例如,其中包含以下代码块:
I'm trying to write some python functions to generate a batch of input files, in which there is, for instance, this block:
***behavior
**energy_phase_1
ef_v 10
**energy_phase_2
ef_v 7.
到目前为止,我正在使用collections.OrderedDict,因为顺序在这种输入文件中很重要.例如,如果我的批处理中有两个模拟:
So far i was using collections.OrderedDict, because order matters in this kind of input file). For instance,if there are two simulations in my batch:
inp_dict['***behavior'] = [ '', '']
inp_dict['**energy_phase_1'] = [ '', '']
inp_dict['**ef_v'] = [ '10', '20']
inp_dict['**energy_phase_2'] = [ '', '']
inp_dict['**ef_v'] = [ '7', '14']
要写入文件,我将做如下操作:
And to write the file I would just do something like:
for s , n in enumerate(sim_list):
......some code...
inp_file.write(' '.join([ key, val[s], '\n' for key, val in inp_dict.items]))
但是,正如您所看到的,这还不够,因为字典中有重复项.
But as you can see, this is not enough, since it there are duplicates key in the dict.
所以我的问题是:是否有一个允许重复键的有序字典?例如,如果存在dict ['key'] = 1和dict ['key'] = 2,则第一个调用将返回1,第二个返回2?
So my question is: is there an ordered dict that allows for duplicate keys? For instance, if there exists dict['key']=1 and dict['key']=2, first call would return 1 and second 2?
或者,是否有一些聪明而简单的方法来实现我想要的愿望?
Or, is there some clever and simple way to achieve want I want?
谢谢
推荐答案
重复键的概念与dict的概念背道而驰.
The concept of duplicate key goes against the concept of dict.
如果您需要维护订单并且有重复的密钥,我想您需要使用其他数据结构.一种可能的解决方案是使用元组列表.类似于以下内容:
If you need to maintain order and have duplicate keys I'd say you need to use another data structure. One possible solution would be using a list of tuples. Something like the following:
inp = list()
# Define your input as a list of tuples instead of as a dict
inp.append(('***behavior', ('', '')))
inp.append(('**energy_phase_1', ('', '')))
inp.append(('**ef_v', ('10', '20')))
inp.append(('**energy_phase_2', ('', '')))
inp.append(('**ef_v', ('7', '14')))
# You can have duplicate keys on the list and the order is preserved
output = "\n".join(["{key} {val}".format(key=t[0], val=t[1][0]).strip() for t in inp])
在这种情况下,output
变量将包含:
In this case the output
variable would contain:
***behavior
**energy_phase_1
**ef_v 10
**energy_phase_2
**ef_v 7
如果您需要通过键访问值(类似dict的功能),则可以使用以下方式:
If you need to access values by key (a dict-like functionality) you could use something like this:
def get_key_values(inp, key):
filtr_by_key = filter(lambda t: True if t[0] == key else False, inp)
return filtr_by_key
ef_v_values = get_key_values(inp, "**ef_v")
在这种情况下,ef_v_values
将仅包含与键**ef_v
关联的值:
In this case the ef_v_values
would contain only the values associated with the key **ef_v
:
[('**ef_v', ('10', '20')), ('**ef_v', ('7', '14'))]
希望这会有所帮助.
这篇关于python命令字典重复键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!