How does .keys method return a list of keys in parenthesis? I mean after getting a list of keys how does python put this list into parenthesis? If I want to write a function that returns list in parenthesis how should I implement that? For example: def foo(): l=[1,2] what should I write so that when I call my function it returns this list l in parenthesis? Thanks in advance
CodePudding user response:
It looks like you might be new to Python. If what you want to do is return a tuple (1, 2)
from a list var =[1, 2]
you can apply the tuple()
function:
>>> var = tuple([1, 2])
>>> var
(1, 2)
In actual fact the dict.keys()
fujnction returns a special iterator called a view, but as the tuple
function takes any iterator as an argument the tuple
function will still work for a view.
>>> d = {1: 'one', 2: 'two'}
>>> tuple(d.keys()
(1, 2)
If this isn't what you want perhaps you can edit the question to explain more clearly what you are trying to do.
CodePudding user response:
def foo(l):
return tuple(l.keys())
A simple test to check the result:
print(foo({1:"one", 2: "two"}))
print(foo({1:"one", 2:"two", 3:"three", 4:"four", "anykey":"anyvalue"}))