[英]Convert the dictionary into tuple and printing it in reverse order
我在 dict 中有值,例如 {"AR":True,"VF":False,"Siss":True}
現在我只提取值為 TRUE 的鍵,所以我只得到 output AR 和 Siss,我正在嘗試將這個 output 保存在元組中,現在想以相反的順序打印出來,例如 ("Siss","AR" )。
下面是我的代碼片段,當我將其轉換為元組時,它以字符而不是字符串的形式向我顯示 output
for i in dic:
if dic[i]==True:
t = tuple(i)
print (t)
Reverse(t)
def Reverse(tuples):
new_tup = tuples[::-1]
return new_tup
如何將這些字符更改為單詞/字符串?
您可以通過以相反的順序遍歷字典並過濾掉非 True 值來輕松完成此操作。
d = {'AR': True, 'VF': False, 'Siss': True}
print(tuple(k for k,v in reversed(d.items()) if v is True))
('Siss', 'AR')
一種功能性方法:
dictionary = { "AR": True, "VF": False, "Siss": True }
filtered = filter(lambda kv: kv[1], reversed(dictionary.items()))
just_key = map(lambda kv: kv[0], filtered)
print(list(just_key))
它的工作原理是:
reversed
- 字典中的鍵值對filter
字典的項目,刪除所有為False
的鍵值對。map
保留密鑰這是一個簡單的逐步方法,它使用列表作為中間體,用字典中的適當鍵填充它,反轉列表,然后將其轉換為元組。
dic = {"AR":True,"VF":False,"Siss":True}
lst = []
for key in dic:
if dic[key]: (# ==True is redundant)
lst.append(key)
lst.reverse()
result = tuple(lst)
print(result)
#('Siss', 'AR')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.