我有一把包含数百个键的词典。如何运行for循环并对不同的键/值对执行比较/算术运算?
以下是字典的一个小例子:
dict = {
"001": {
"d": "7179.6201",
"f": "7183.6201",
},
"002": {
"d": "7112.0200",
"f": "7166.0000",
},
"003": {
"d": "7255.0000",
"f": "7128.5400",
},
"004": (
"d": "7250.0000",
"f": "7128.2000"
}
}
for循环应遍历每个键/值对并执行两个操作。 (1)如果“001”(或任何键)的“d”值大于“002”(或任何键+ 1)的“d”值,则返回键(“001”,对于此特定值迭代)及其对应的“d”值。 (2)如果“d”值大于下面的“d”值,则减去两个数字(从字符串转换为数字)并返回差值。
在此特定字典上运行代码所需的结果:
"001": "7179.6201", diff: "67.6001"
"003": "7255.0000", diff: "5.0000"
我理解如何调用这些键/值对,但我甚至不知道如何开始比较不同键的值,尤其是当我无法明确引用键本身时。我想为我所做的事情提供代码,但我甚至不知道从哪里开始这样的事情。
谢谢!
答案 0 :(得分:1)
如果您的按键遵循该顺序,您可以从当前按键
获取下一个按键for key in data:
next_key = "{:03d}".format(int(key) + 1)
try:
current_d, next_d = data[key]['d'], data[next_key]['d']
except KeyError:
print('End of data')
else:
d_diff = float(current_d) - float(next_d)
if d_diff > 0:
print('{}: {}, diff: {}'.format(key, current_d, d_diff))
答案 1 :(得分:1)
from collections import OrderedDict
dict1 = {"001": {"d": "7179.6201", "f": "7183.6201"}, "002": {"d": "7112.0200", "f": "7166.0000"},
"003": {"d": "7255.0000", "f": "7128.5400"}, "004": {"d": "7250.0000","f": "7128.2000"}}
dict1 = OrderedDict(dict1)
for index in range(len(dict1) - 1):
if float(list(dict1.items())[index][1]['d']) > float(list(dict1.items())[index + 1][1]['d']):
print(list(dict1.items())[index][0] + ':' + list(dict1.items())[index][1]['d'] + " diff:" + \
str(float(list(dict1.items())[index][1]['d']) - float(list(dict1.items())[index+1][1]['d'])))
else:
pass
说明:
首先使用collections.OrderedDict()
确保字典具有序列顺序from collections import OrderedDict
dict1 = OrderedDict(dict1)
使用for循环迭代直到最后一个元素:
for index in range(len(dict1) - 1):
使用if语句比较当前索引的“d”值和下一个索引:
if float(list(dict1.items())[index][1]['d']) > float(list(dict1.items())[index + 1][1]['d']):
如果确实如此,请打印您需要的格式,并同时添加差异。
print(list(dict1.items())[index][0] + ':' + list(dict1.items())[index][1]['d'] + " diff:" + \
str(float(list(dict1.items())[index][1]['d']) - float(list(dict1.items())[index+1][1]['d'])))
注意:这是在我的机器上使用python == 3.6测试的,并得到了你想要的输出!!