[英]How to get specific number of elements from dict in python from middle
我有字典
dict1 = {"one":"1", "two":"2", "three":"3", "four":"4", "five":"5"}
現在我不想再解釋說dict2
其中包含的第二和第三個元素dict1
我怎樣才能做到這一點,請幫助謝謝
這是一個單行使用.items()
來獲取(key, value)
對的迭代,以及使用dict
構造函數從這些對的切片中構建一個新字典:
>>> dict(list(dict1.items())[1:3])
{'two': '2', 'three': '3'}
切片索引是 1(包含)和 3(不包含),因為索引從 0 開始計數。請注意,這使用項目在原始字典中的任何順序,這將是它們插入的順序(除非使用舊版本的 Python ,在這種情況下,順序通常是不確定的)。 如果您想要不同的順序,您可以使用sorted
而不是list
,也許使用適當的key
功能。
dict2 = {}
pos = 0
for x in dict1:
if(pos == 1 or pos == 2):
dict2[x] = dict1[x]
pos += 1
在一行中
dict2, positions = {}, (2, 3)
[dict2.update({key: dict1[key]}) for i, key in enumerate(dict1.keys()) if i in positions]
print(dict2)
試試這個 -
dict1 = {"one":"1", "two":"2", "three":"3", "four":"4", "five":"5"}
dict2 = {}
list1 = ['two','three'] # The elements you want to copy
for key in dict1:
if key in list1:
dict2[key] = dict1[key]
print(dict2)
結果:
{'two': '2', 'three': '3'}
或者,或者——
for i in list1:
dict2[i] = dict1[i]
print(dict2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.