简体   繁体   中英

how to return a tuple from a dictionary that satisfy True value parameter in Python

I have the following dictionary and I need to return the dictionary keys that only have a TRUE value as a tuple. For example, given my dictionary below the function should return ("madam", "1221").

revDict = {'hello world': False, 'madam': True, '1221': True}

I tried few way but non of them works:

#1

myTrueDict = (i for i in revDict if revDict.values() = True)
print(myTrueDict)
myTuple = tuple(myTrueDict.keys())
print(myTuple)

#2

myTrueDict = {k:v for (k,v) in revDict.items() if v = True}
print(myTrueDict)
myTuple = tuple(myTrueDict.keys())
print(myTuple)

Your second solution works if you fix a typo with if v = True where it should be if v == True

revDict = {'hello world': False, 'madam': True, '1221': True}
myTrueDict = {k:v for (k,v) in revDict.items() if v == True}
myTuple = tuple(myTrueDict.keys())
print(myTuple)

However, you could simply get the keys ignoring the values as:

tuples = tuple(k for k, v in revDict.items() if v)
print(tuples)

Here is a working proposal according to your #1 example:

revDict = {'hello world': False, 'madam': True, '1221': True}
myTrueDict = tuple(i for i in revDict if revDict[i] == True)
print(myTrueDict)

Output:

('madam', '1221')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM