将以空格分隔的输入项添加到字典中。蟒蛇

时间:2013-04-02 00:21:50

标签: python loops input dictionary spaces

我需要制作一个程序,要求用户进入城市,然后进入温度。城市和温度被空间隔开。当用户输入“停止”时,程序停止询问输入并报告最冷的城市。您可以随时假设用户输入一个城市,然后输入一个空格,然后输入温度。

Sample Output:

Enter city followed by temperature > Edmonton -2
Enter city followed by temperature > Toronto 3
Enter city followed by temperature > Vancouver -1
Enter city followed by temperature > Ottawa -3
Enter city followed by temperature > stop
{'Toronto': 3, 'Edmonton': -2, 'Vancouver': -1, 'Ottawa': -3}
The coldest city is Ottawa -3

我遇到的问题是如何将输入的项目输入字典表单。我不明白它如何与输入项目中的空间一起工作。我有三个其他程序遵循这种格式,输入包括空格,我真的无法弄清楚/找到如何解决它。任何帮助将不胜感激。

PS:我在初学者的计算科学课程中......是啊..

3 个答案:

答案 0 :(得分:1)

您需要使用split()方法将输入拆分为键和值部分。

答案 1 :(得分:0)

ipython会话示例:

In [1]: a = raw_input('City temp: ')
City temp: Edmonton -2

In [2]: a
Out[2]: 'Edmonton -2'

In [3]: d = {}

In [4]: a = a.split()

In [5]: d[a[0]] = a[1]

In [6]: d
Out[6]: {'Edmonton': '-2'}

显然有更多的pythonic方法可以做到这一点。您可以通过阅读the documentation

来解决这些问题 祝你好运!

答案 2 :(得分:0)

您想使用string.split()

d = {}
for i in range(5):
    user = input('Enter city followed by temperature') 
    # use raw_input(prompt) if using Python 2.x
    data = user.split()
    d[data[0]] = int(data[1])

或者,您可以将每对作为元组附加到列表中,然后使用dict()函数:

dataPoints = []
for i in range(5):
    user = input('Enter city followed by temperature')
    data = user.split()
    dataPoints.append((data[0], int(data[1])))
d = dict(dataPoints)