I am learning python and I don’t get why this simple piece of code does not work.
list = {"Text":"Text"}
print(list)
if list.keys() == list.values():
print("True")
else:
print("False")
This returns False
when it should return True
.
CodePudding user response:
keys()
and values()
don't return lists, they return iterator objects that yield the keys and values. If you want to compare the contents, convert them to lists, using the list()
function.
You won't be able to do this in your snippet because you've redefined the name list
to your dictionary. You should use a variable name that isn't the same as a built-in function.
my_dict = {"Text":"Text"}
print(my_dict)
if list(my_dict.keys()) == list(my_dict.values()):
print("True")
else:
print("False")
CodePudding user response:
The type of dict.keys() and dict.values() is different so must cast both to a list object to compare.
data = {"Text":"Text"}
a = data.keys()
b = data.values()
print(a)
print(b)
print(a == b) # False
if list(a) == list(b):
print("True")
else:
print("False")
Output:
dict_keys(['Text'])
dict_values(['Text'])
False
True