Python中文
首页
教程
问答
标签
搜索
登录
注册
如何在提取字典的子集后保持顺序
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我想做一本词典(或列表),它是另一本词典的子集。请看下面我的代码:</p> <pre><code>ThePythons = { 'GC': 'Graham Chapman', 'JC': 'John Cleese', 'EI': 'Eric Idle', 'MP': 'Michael Palin' } query = ['EI', 'JC'] output = {key: value for key, value in ThePythons.items() if key in query} print(output) </code></pre> <p>有时输出为:</p> <pre><code>{'JC': 'John Cleese', 'EI': 'Eric Idle'} </code></pre> <p>有时是:</p> <pre><code>{'EI': 'Eric Idle', 'JC': 'John Cleese'} </code></pre> <p>如何保持(保存)输出与查询的顺序完全相同?我希望输出始终为:</p> <pre><code>{'EI': 'Eric Idle', 'JC': 'John Cleese'} </code></pre> <p>输出也可以是列表类型(<code><class 'list'></code>)。例如:</p> <pre><code>[['EI', 'Eric Idle'], ['JC', 'John Cleese']] </code></pre>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>字典是无序的。你必须使用列表理解而不是字典理解来保持顺序:</p> <pre><code>output = [(key, ThePythons[key]) for key in query] </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何在python中从数据帧列中删除分类值?
6 回答
如何在python中从数据帧列表中删除引号
5 回答
如何在python中从数据帧创建列表
2 回答
如何在Python中从数据帧创建嵌套的JSON
2 回答
如何在Python中从数据帧显示wordcloud
6 回答
如何在Python中从数据帧的时间戳中删除字符
4 回答
如何在Python中从数据帧绘制简单绘图?
6 回答
如何在python中从数据帧行提取具有特定长度的范围?
9 回答
如何在python中从数据帧设置dict中的值
1 回答
如何在Python中从数据库中获得一个结果
4 回答
如何在python中从数据框中绘制分类条形图
4 回答
如何在Python中从数据框中选择特定细节?
10 回答
如何在python中从数据集中删除unicode
10 回答
如何在python中从数据集中删除某些数值?
7 回答
如何在python中从数据集中选择行
1 回答
如何在Python中从数组中删除元素
8 回答
如何在python中从数组中删除单个倒逗号?
7 回答
如何在python中从数组中删除对象?
2 回答
如何在python中从数组中删除引号
7 回答
如何在python中从数组中删除所有最小值
7 回答