如何向后打印字典中的键

时间:2016-07-18 15:22:59

标签: python-2.7 dictionary

我有一本字典,我想要向后读取每个单独的键,直到它到达下划线。一旦它到达下划线,它应该停止,所以我可以将其项目设置为等于新变量。

据我所知,我可以使用str.partition()分隔某个字符并且可以使用[:: - 1]向后读取字符串,但我不知道如何将它们与字典一起使用。

    Payload_Values = {'Voltage_asleep(V)' : 10, 'Current_asleep(A)' : 5, 'Wattage_asleep' : 50}
    for c in (Payload_Values.keys())
        Payload_Values.partition(_)

1 个答案:

答案 0 :(得分:0)

您需要使用keys()items()而非iteritems()迭代dict,在Python3中需要将这些迭代器转换为列表,否则如果添加新元素则会导致错误在迭代时给dict(我只是提到,在你的例子中这没关系)。否则,您接近解决方案。我完全不明白,你想用钥匙做什么?打印出来吗?在最后一个下划线之后参加?设置一个新的键值对?在不知情的情况下,我试图展示所有组合,如果您需要其他内容,请详细询问:

# this is because Python3 compatibility:
from __future__ import print_function
from future.utils import iteritems

for key, val in iteritems(Payload_Values):
    # new key is the part after the last underscore
    # or the whole string, if it does not contain underscore:
    new_key = key.split('_')[-1]

    # new key is the elements separated by `_`, reversed
    # and rearranged to a string:
    key_rev = '_'.join(key.split('_')[::-1])

    # new key is the complete string reversed:
    new_key = key[::-1]

    #
    # set a new element with the new key:
    Payload_Values[new_key] = 'your new value'

    # print the new key:
    print(new_key)

# if you want to modify the dict in this loop:
for key, val in list(Payload_Values.items()):
    # ...
    Payload_Values[some_key] = some_value