[英]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.