如何在python中打印未排序的字典? [英] How to print unsorted dictionary in python?

查看:133
本文介绍了如何在python中打印未排序的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有这个dict:

  d = {} 
d ['b'] ='beta '
d ['g'] ='gamma'
d ['a'] ='alpha'

当我打印dict;

  for k,v in d.items():
打印k

我得到这个;

  a 
b
g

像python自动排序dict!如何获得原始未分类的列表?



Gath

解决方案

Dicts不能这样工作


CPython实现细节:键和值以任意顺序列出,这是非随机的,因Python实现而异,并且取决于字典的历史的插入和删除。


您可以使用带有2元组的列表:



'pre> d = [('b','beta'),('g','gamma'),('a','alpha')]

类似但更好的解决方案在韦恩的回答


I have this dict in python;

d={}
d['b']='beta'
d['g']='gamma'
d['a']='alpha'

when i print the dict;

for k,v in d.items():
    print k

i get this;

a
b
g

it seems like python sorts the dict automatically! how can i get the original unsorted list?

Gath

解决方案

Dicts don't work like that:

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

You could use a list with 2-tuples instead:

d = [('b', 'beta'), ('g', 'gamma'), ('a', 'alpha')]

A similar but better solution is outlined in Wayne's answer.

这篇关于如何在python中打印未排序的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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