简体   繁体   中英

how to print only one key of a python dictionary per line

so have this dict avgTemp = {1945: 51.75, 1946: 52.95, 1947: 51.92, 1948: 51.61,....} where the key correspond to year and the value is the avg temperature. i use map to map out the value of the dict with:

FahrtoCelc = list(map(lambda x:((x - 32) * 5 / 9), avgTemp.values()))

then i want to print out this value correspond to the year in the dict using:

for i in range(len(avgTemp )):
print(avgTemp.keys(), " : ", FahrtoCelc[i])

but end up with an answer that is not as i wanted it, how do i print 'year: converted temp'

Try this:

avgTemp = {1945: 51.75, 1946: 52.95, 1947: 51.92, 1948: 51.61}

for year, temperature in avgTemp.items():
    print(f"{year} - {round((temperature - 32) * 5 / 9, 2)}C")

Output:

1945 - 10.97C
1946 - 11.64C
1947 - 11.07C
1948 - 10.89C

Use dict comprehension to save keys in FahrtoCelc variable:

FahrtoCelc = {year: ((x - 32) * 5 / 9) for year, x in avgTemp.items()}

for year, temperature in FahrtoCelc:
    print(year, ":", temperature)

You should use the items() method of your dictionary:

avgTemp = {1945: 51.75, 1946: 52.95, 1947: 51.92, 1948: 51.61}

print(*(f"{y} : {(t-32)*5/9:02.2f}°C" for y,t in avgTemp.items()),sep="\n")

1945 : 10.97°C
1946 : 11.64°C
1947 : 11.07°C
1948 : 10.89°C

If you want to play with map(), you can use it in place of the comprehension:

FtoC = lambda yt: f"{yt[0]} : {(yt[1]-32)*5/9:02.2f}°C"

print(*map(FtoC,avgTemp.items()),sep="\n")

without format strings:

FtoC = lambda yt: str(yt[0]) + " : " + str(round((yt[1]-32)*5/9,2)) + "°C"

Another way is to use the join statement which gives this one-liner:

print('\n'.join('{} - {}'.format(*item) for item in avgTemp.items()))

Since you want to use map you have to apply it when creating the new dictionary.

avgTemp = {1945: 51.75, 1946: 52.95, 1947: 51.92, 1948: 51.61,}
celsius = dict(map(lambda x: (x[0], (x[1] - 32) * 5 / 9), avgTemp.items()))

Now you can loop over the celsius dictionary.

for key, value in celsius.items():
    print(f'{key}: {value}°C' 

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