【问题标题】:how to return a list of values for dictionary and populate them into a list?如何返回字典的值列表并将它们填充到列表中?
【发布时间】:2017-03-07 06:00:07
【问题描述】:
dctCourses = {1000:'Intro to IS',1505:'Fundamentals of Programming',1515:'Web Programming Overview',2550:'Visuals Basic I',2560:'Visual Basic II'}

lstCourseKeys = []

index5 = 0

for key in dctCourses:
    lstCourseKeys.append(key)
    index5 =index5 + 1

lstCourseKeys.sort()

index6 = 0

for item in lstCourseKeys:
    print(item)
    index6 = index6 + 1

lstCourseValues = []

index7 = 0

for value in dctCourses:
    lstCourseValues.append(value)
    index7 =index7 + 1

lstCourseValues.sort()

index8 = 0

for item in lstCourseValues:
    print(item)
    index8 = index8 + 1

我创建了一个字典,需要创建一个存储键的列表和一个存储值的列表,并将两个列表打印回一个排序列表。当我运行上面的代码时,我得到了这个

1000
1505
1515
2550
2560
1000
1505
1515
2550
2560

似乎键列表按预期工作,但我的值列表似乎填充键而不是值。我错过了什么还是需要改变什么?

【问题讨论】:

  • 如给定的答案:使用iteritemsfor value in dctCourses 不能以这种方式工作,因为 value 只是一个变量名。与您之前的循环没有区别。见here

标签: python-2.7 list dictionary


【解决方案1】:

对于第一部分,keys,您可能想要使用dctCourses.iteritems()

for key,_ in dctCourses.iteritems():   #`_` ignores the values
    ...

values类似:

for value in dctCourses.values():      # only getting values
    ...

输出:

1000
1505
1515
2550
2560
Fundamentals of Programming
Intro to IS
Visual Basic II
Visuals Basic I
Web Programming Overview

检查两者仍然是列表:

print type(lstCourseKeys)
print type(lstCourseValues)
<type 'list'>
<type 'list'>

【讨论】:

  • 感谢您的帮助。我还发现将“dctCourses 中的值:lstCourseValues.append(value) index7 =index7 + 1”更改为“dctCourses 中的值:lstCourseValues.append(dctCourse.get(value)) index7 =index7 + 1”效果也很好,尽管我认为这是一种肮脏的做法
  • 欢迎。当然,我想有很多方法可以完成它,我不知道什么是干净的或脏的,无论哪种方式都能完成工作。很高兴它有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多