Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

python - Putting a list of integers into an existing dictionary

This is the Bonus part of the "Mountain Heights 3" exercise from http://introtopython.org/dictionaries.html.

I have this dictionary which shows 5 mountains and their heights in meters.

mountains_meters = {'Mount Everest' : 8848,
                    'K2' : 8611,
                    'Kangchenjunga' : 8586,
                    'Lhotse' : 8516,
                    'Makalu' : 8485,
                    }

and the question asks to define a function that reads through the height in meters and returns a list of the height in feet, given the conversion 1 meter = 3.28 feet.

feet = []
def meters_to_feet(dictionary):
    for value in dictionary.values(): 
        feet.append(round(value * 3.28))

The question then asks to create a nested dictionary with the structure {'everest': [8848, 29021]}

I'm unsure how to get my list of heights in feet into the existing mountains_meters dictionary.

[29021, 28244, 28162, 27932, 27831] into

mountains_meters = {'Mount Everest' : 8848,
                    'K2' : 8611,
                    'Kangchenjunga' : 8586,
                    'Lhotse' : 8516,
                    'Makalu' : 8485,
                    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why don't you do it in a single loop?

for k,v in mountains_meters.items():
    mountains_meters[k] = [v, round(v*3.28)]
    feet.append(round(v * 3.28))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...