【问题标题】:parser dict in python [closed]python中的解析器字典[关闭]
【发布时间】:2013-10-25 16:38:42
【问题描述】:

我有一个类似的字典:

test =  {0: {'nom': 'toto', 'id':1}, 2: {'nom': 'tutu', 'id': 2}}

我想打印一个类似的结果

toto

tutu

我试试

for nom in test :
   print test['nom']

但不工作

谢谢

【问题讨论】:

  • 谁是投票反对这个问题的人?你没看到他是新来的吗?嘘
  • @YankiTwizzy 尽管人们能够弄清楚“但不工作”是什么意思,但在没有解释这意味着什么的情况下说“它不工作”仍然被认为是不好的形式(编译错误?输出不是你所期望的?计算机爆炸了?)以及当前正在发生的事情的输出。我没有投反对票,但我猜这就是人们投反对票的原因。

标签: python dictionary


【解决方案1】:

因为你的第一个字典的键是数字。不是“名义”。

for k in test:
    print test[k]['nom']

【讨论】:

    【解决方案2】:
    for nom in test:
           print (test[nom]['nom'])
    

    这应该适用于 Python 3 和 2。使用以下内容仅适用于 2

    for nom in test:
               print test[nom]['nom']
    

    【讨论】:

      【解决方案3】:
       test = {0: {'nom': 'toto', 'id':1}, 2: {'nom': 'tutu', 'id': 2}}
      
       print ' '.join([test[ele]['nom'] for ele in test])
      

      【讨论】:

      • 你的意思是values() 吗?
      • 不,@karthikr,它的.keys(),其中test.keys() 会以列表的形式为您提供所有第一级键
      • 如果你的意思是keys,那么最好完全省略它。
      猜你喜欢
      • 1970-01-01
      • 2021-10-25
      • 2010-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 2016-11-24
      相关资源
      最近更新 更多