简体   繁体   English

python命令字典重复键

[英]python ordered dict with duplicates keys

I'm trying to write some python functions to generate a batch of input files, in which there is, for instance, this block: 我正在尝试编写一些python函数来生成一批输入文件,例如,其中包含以下代码块:

***behavior
**energy_phase_1
ef_v 10
**energy_phase_2
ef_v 7.

So far i was using collections.OrderedDict, because order matters in this kind of input file). 到目前为止,我正在使用collections.OrderedDict,因为顺序在这种输入文件中很重要)。 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. 但是,您可以看到,这还不够,因为字典中有重复项。

So my question is: is there an ordered dict that allows for duplicate keys? 所以我的问题是:是否有一个允许重复键的有序dict? For instance, if there exists dict['key']=1 and dict['key']=2, first call would return 1 and second 2? 例如,如果存在dict ['key'] = 1和dict ['key'] = 2,则第一个调用将返回1,第二个返回2?

Or, is there some clever and simple way to achieve want I want? 或者,是否有一些聪明而简单的方法来实现我想要的?

Thanks 谢谢

The concept of duplicate key goes against the concept of dict. 重复键的概念与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])

In this case the output variable would contain: 在这种情况下, output变量将包含:

***behavior
**energy_phase_1
**ef_v 10
**energy_phase_2
**ef_v 7

If you need to access values by key (a dict-like functionality) you could use something like this: 如果您需要通过键(类似于dict的功能)访问值,则可以使用以下方法:

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")

In this case the ef_v_values would contain only the values associated with the key **ef_v : 在这种情况下, ef_v_values仅包含与键**ef_v相关联的值:

[('**ef_v', ('10', '20')), ('**ef_v', ('7', '14'))]

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM