python 3.6中的字典顺序与旧版本 [英] Dict order in python 3.6 vs older

查看:55
本文介绍了python 3.6中的字典顺序与旧版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过制表运行代码时,我需要按照确切的顺序(访问者团队,访客评分,主队,住房评分,预期获胜者,保证金)打印出一些代码.

  final_dict = {'Visitor Team':visitor_team,'Visitor Rating':visitor_rating,'Home Team':home_team,房价":home_rating,预期获胜者":expected_winner,保证金":expected_winner_diff}print(tabulate(final_dict,headers ="keys",floatfmt =.2f",tablefmt ="fancy_grid")) 

我一直在学习和使用Python 3.6,并且我不知道,现在已经订购了3.6中的命令,因此它实际上可以按照我的意图打印出来.我想Python 3.6确实给了我所需的东西,真是愚蠢!

但是我去了另一台计算机上安装Python 3.5,但并没有打印出我想要的样子.我一直在阅读有关orderdicts的文章,但不确定如何使用它.我是否需要先将final_dict声明为空,然后将其迭代所需的键顺序?

解决方案

Python 3.6中的字典是有序的,但是该功能被视为您不应该依赖的实现细节(在某些特殊情况下,例如** kwargs ).如果确实需要特定的订单,则应改用 collections.OrderedDict .您可以使用按所需顺序排列的键,值元组的列表构造一个:

来自集合的

 导入OrderedDictfinaldict = OrderedDict([('Visitor Team',visitor_team),(访问者评分",visitor_rating),(主队",home_team),(房价","home_rating"),(预期获胜者",expected_winner),(保证金",expected_winner_diff),]) 

除了具有不同的 repr 和一些其他方法外, OrderedDict 在大多数方面都像普通的 dict 一样工作.您可以在文档中了解有关此内容的更多信息..>

在Python 3.6及更高版本中,如果您的键字符串是有效的标识符(例如 OrderedDict(Margin = expected_winner_diff)),您还可以在构造函数中使用关键字参数.与普通 dict 的顺序不同,可以保证保留关键字的顺序(而不是实现细节).但这不是向后兼容的(无论如何也不能用于您的非标识符键).

但是可能值得考虑的是,如果您需要一个非常特定的数据顺序,则字典可能不是最好的存储类型.我看到的是 tabulate 函数使用来自一个库,根据文档,它接受许多不同格式的数据.我可能只是将其传递给列数据列表,并分别为其提供标题:

  data = [visitor_team,visitor_rating,home_team,home_rating,expected_winner,expected_winner_diff]标头= [访客团队",访客评分",主队",房屋评级",预期获胜者",保证金"]打印(制表(数据,标题=标题,floatfmt =.2f",tablefmt ="fancy_grid")) 

(注意,由于我的系统上没有 tabulate 库,因此我尚未实际测试过该代码.但这至少应该可以正常工作了.)

I have this bit of code that I need printed out in this exact order (Visitor Team, Visitor Rating, Home Team, Home Rating, Expected Winner, Margin) when I run it through tabulate.

final_dict = {'Visitor Team': visitor_team, 'Visitor Rating': visitor_rating, 'Home Team': home_team,
              'Home Rating': home_rating, 'Expected Winner': expected_winner, 'Margin': expected_winner_diff}

print(tabulate(final_dict, headers="keys", floatfmt=".2f", tablefmt="fancy_grid"))

I've been learning and using Python 3.6 and, unbeknownst to me, dicts in 3.6 are ordered now so this actually prints out as I intended it to. It was just dumb luck I guess that Python 3.6 gave me exactly what I needed!

But I went to install Python 3.5 on another computer and this doesn't print out like I want. I've been reading about ordereddicts but I'm not sure how exactly to use it. Do I need to declare final_dict as empty first and then iterate into it the key order I need?

解决方案

Dictionaries in Python 3.6 are ordered, but that feature is considered an implementation detail that you shouldn't rely upon (except in a few specific cases like **kwargs). If you do require a specific order, you should use collections.OrderedDict instead. You can construct one using a list of key, value tuples that are in the desired order:

from collections import OrderedDict

finaldict = OrderedDict([('Visitor Team', visitor_team),
                         ('Visitor Rating', visitor_rating),
                         ('Home Team', home_team),
                         ('Home Rating', home_rating),
                         ('Expected Winner', expected_winner),
                         ('Margin', expected_winner_diff),
                        ])

An OrderedDict works just like a normal dict in most respects, other than having a different repr and a few additional methods. You can read more about it in the docs.

In Python 3.6+ you'd also be able to use keyword arguments to the constructor if your key strings were valid identifiers (e.g. OrderedDict(Margin=expected_winner_diff)). Unlike the ordering of normal dicts, the order of keywords is guaranteed to be preserved (not an implementation detail). That's not backwards compatible though (and can't work for your non-identifier keys anyway).

But it's probably worth considering that if you need a very specific order for your data, a dictionary may not be the best type to use to store it in. I see the tabulate function you're using comes from a library, and according to the docs, it accepts many different formats of data. I'd probably just pass it a list of column data, and give it the headers separately:

data = [visitor_team, visitor_rating, home_team,
        home_rating, expected_winner, expected_winner_diff]

headers = ["Visitor Team", "Visitor Rating", "Home Team",
           "Home Rating", "Expected Winner", "Margin"]

print(tabulate(data, headers=headers, floatfmt=".2f", tablefmt="fancy_grid"))

(Note, I've not actually tested that code, since I don't have the tabulate library on my system. But it should at least be close to working.)

这篇关于python 3.6中的字典顺序与旧版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆