Python 2.7 2D 字典

2024-04-25 19:23:38 发布

您现在位置:Python中文网/ 问答频道 /正文

Dict = {}
target = [
    ['55.0', 'Index', '0', '18512'],
    ['55.0', 'Index', '0', '18513']]
for input in target:

    temperature, hum, out = input[0], input[1], input[2:]
    Dict.setdefault(temperature, {}).setdefault(hum, out)
print Dict

我想结果是 {'55.0': {'Index': ['0', '18512']}}, {'55.0': {'Index': ['0', '18513']}}

但实际结果只有{'55.0': {'Index': ['0', '18512']}}

我该怎么修?你知道吗


Tags: intargetforinputindexoutdictprint
2条回答

你要的是一份字典清单:

list_of_dicts = []
target = [
    ['55.0', 'Index', '0', '18512'],
    ['55.0', 'Index', '0', '18513']]
for input in target:
    temperature, hum, out = input[0], input[1], input[2:]
    list_of_dicts.append({temperature: {hum: out}})
print list_of_dicts

输出

[{'55.0': {'Index': ['0', '18512']}}, {'55.0': {'Index': ['0','18513']}}]

但是,如果您想让一个字典有两个'55.0'键和嵌套的字典'hum: out',那是不可能的,因为字典可以有unqiue键,所以您的第二个项总是会覆盖第一个项。你知道吗


还有一些注意事项:

1.)setdefault()非常适合在键不存在的情况下默认键的项值,但是在您的用例中,它会适得其反,因为您的键不是唯一的,因此每次都会覆盖该值。在这种特殊情况下,只需为每个项目创建一个字典,append()到生成的list就足够了。你知道吗

2.)尽量避免使用保留关键字,如inputdict。尽管您已经大写了Dict,但是很容易引入错误,比如覆盖一些内置功能。Python的建议命名约定是对变量/属性使用小写和下划线,对类使用大写DWORD。Read more about it on the documentation here。这只是一个建议,你可以有自己的风格。但是,通过遵循一组一致的约定,您的代码将更易于调试。你知道吗

from collections import defaultdict
target = [
    ['55.0', 'Index', '0', '18512'],
    ['55.0', 'Index', '0', '18513']]
main_dict = []
for tar in target:
    key, index, list_ = tar[0], tar[1], tar[2:]
    local_dict = defaultdict(dict)
    local_dict[key].update({index:list_})
    main_dict.append(dict(local_dict))
print(main_dict)
>>>[{'55.0': {'Index': ['0', '18512']}}, {'55.0': {'Index': ['0', '18513']}}]

相关问题 更多 >

    热门问题