简体   繁体   中英

Iteration through a dictionary using a function

why does does code1 output all the values in the dictionary and code2 only outputs one item

my code1:

resources = {
"water": 300,
"milk": 200,
"coffee": 100, }                                                                             
def available(dict):
    for k,v in dict.items():
        print(f'{k}:{v}')

available(resources)

output1:

water:300
milk:200
coffee:100

my code2

resources = {
"water": 300,
"milk": 200,
"coffee": 100,}                                                                             
def available(dic):
    for char in dic:
        return f'{char}:{dic[char]}'                                  
print((available(resources)))

output2

water:300

In code1 you are using print which is not going to terminate the function, while on code2 you use return . The return statement terminates immediately the function execution and returns that value.

If you want to return all values in code2 and print them in the same way as in `code`` use the following:

resources = {
"water": 300,
"milk": 200,
"coffee": 100,}                                                                             
def available(dic):
    return [f'{char}:{dic[char]}' for char in dic]

# here we join all the elements in the list using '\n'
print('\n'.join(available(resources))) ```

return keyword is used to mark the end of the function. So your function ends when return statement is executed. Then, only one element is iterated before return... so only one value is printed.

What you are probably looking for is

def available(dic):
    return [f'{char}:{dic[char]} for char in dic]'

In my code2 you are calling return instead of print .

If you want to return the string printed from my code1 , modify my code2 to look like:

resources = {
"water": 300,
"milk": 200,
"coffee": 100,}
                                                                             
def available(dic):
    s = ''
    for char in dic:
        s += f'{char}:{dic[char]}\n'
    return s
                                  
print((available(resources)))

it because of return command. it just return one value from your function. you can test this with this code:

resources = {
"water": 300,
"milk": 200,
"coffee": 100,}                                                                             
def available(dic):
    for char in dic:
        print( f'{char}:{dic[char]}')                                 
available(resources)

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