![](/img/trans.png)
[英]Pythonic way to create a dictionary from a list where the keys are the elements that are found in another list and values are elements between keys
[英]What is the Pythonic way to use (elements of) a list as keys in a dictionary?
給出清單:
keys = ['Orange','Blue','Green']
和字典
colors = {}
什么是使用(元素) keys
作為colors
keys
的最Pythonic方式? 我目前正在做以下事情,但想知道是否有比這更好的使用Python的方法。
for key in keys:
colors[key] = []
編輯 :這個問題最初要求“使用keys
作為colors
keys
的最Pythonic方式”,但隨后的代碼片段表明實際需要的是一種使用其元素的方法。
你可以使用dict理解:
In [1]: keys = ['Orange', 'Blue', 'Green']
In [2]: colors={key: [] for key in keys}
In [3]: colors
Out[3]: {'Blue': [], 'Green': [], 'Orange': []}
對於python 2.6:
In [4]: colors = dict((key, []) for key in keys)
In [5]: colors
Out[5]: {'Blue': [], 'Green': [], 'Orange': []}
如果訂單很重要,請使用tuple
。
In [113]: keys = ['Orange','Blue','Green']
In [114]: colors = {}
In [115]: colors[tuple(keys)] = 0
In [116]: colors
Out[116]: {('Orange', 'Blue', 'Green'): 0}
如果訂單無關緊要,請使用frozenset
。 frozenset
基本上為您提供了一個可frozenset
set
,該set
無法修改,但具有set
所有優點(O(1)查找等)
In [117]: colors = {}
In [118]: colors[frozenset(keys)] = 0
In [119]: colors
Out[119]: {frozenset(['Orange', 'Blue', 'Green']): 0}
如果您希望keys
每個元素都是colors
鍵:
In [120]: colors = {k:[] for k in keys}
In [121]: colors
Out[121]: {'Blue': [], 'Green': [], 'Orange': []}
如上所述的Dict理解是要走的路。 為了顯示替代方法,如果要使用列表進行實例化,還可以將defaultdict
與fromkeys
結合使用:
In [1]: from collections import defaultdict
In [2]: keys = ['Orange','Blue','Green']
In [3]: colors = defaultdict.fromkeys(keys, list)
In [4]: colors['Orange']
Out[4]: <type 'list'>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.