python重复命令_python命令字典重复键

本文探讨了在Python中如何处理包含重复键的输入文件生成问题。通过使用列表加元组的数据结构代替有序字典,既保留了键值对的顺序,又允许键的重复出现。此外,还提供了一种通过定义函数来获取特定键的所有值的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1586010002-jmsa.png

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.

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.

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?

Thanks

解决方案

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

In this case the output variable would contain:

***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:

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', ('10', '20')), ('**ef_v', ('7', '14'))]

Hope this helps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值