【问题标题】:Getting the unique names of a specific value from several keys of a dictionary in python从python中字典的几个键中获取特定值的唯一名称
【发布时间】:2015-10-02 16:15:07
【问题描述】:

我有一些关于字典的数据。字典中的每个键都有几个值,其中一个称为“州”,可以等于乔治亚州、华盛顿州等。我想获得唯一的州。我试过这样做,但我得到一个不正确的语法错误

s = set( value for key in r value = key['state'] )

我怎样才能得到所有的状态?

编辑:

我拥有的数据结构实际上是一个字典列表,所以我想获取 r[0]['state']、r[1]['state'] 等的值并制作一个唯一列表。

【问题讨论】:

  • key state 的值是否可迭代?你能把你的价值添加到这个问题中吗?
  • 你能贴出你正在使用的字典吗?
  • 独特状态是什么意思?他们的关键价值观会改变吗?或者“状态”是否包含所有状态的列表?
  • 字典有点大。也许我可以展示其中的一把钥匙。如果字典是 r 那么如果我打印 r[0]['state'] 我会得到格鲁吉亚。我想获得每个键的状态值上出现的状态的唯一列表。
  • @Atirag r 是字典列表吗?

标签: python dictionary key unique


【解决方案1】:

根据您的评论,因为您有一个字典列表,您可以使用 map 函数并将 dict.get 方法传递给它,以获取所有 state 值,然后您可以遍历 set 中的值:

s = set( value for value in map(lambda x:x.get('state'),r))

或者你可以使用lambda 函数来使用operator.itemgetter

from operator import itemgetter
s = set( value for value in map(itemgetter('state'),r))

【讨论】:

  • 我收到了这个错误 TypeError: descriptor 'get' requires a 'dict' object but received a 'str'
  • 再问一个问题以防万一。有没有一种方法可以计算一个状态显示修改该代码的次数?例如发现阿拉巴马州的次数
【解决方案2】:

所以你有一个字典,每个键值对在value 中都有另一个字典,其中这些“内部”字典的键之一是state

在这种情况下:

my_dict = {'somekey': {'a':1,'b':2, 'state':'georgia'}, 'otherkey': {'a':1,'b':2, 'state':'washington'}}
[val['state'] for key, val in my_dict.iteritems()]
['georgia', 'washingon']

【讨论】:

    【解决方案3】:

    只是猜测你的数据结构,但如果是这样的话:

    r = {'home': {'address': '123 Oak Avenue', 'city': 'My town', 'state': 'State'},
         'work': {'address': '456 Main Street', 'city': 'Big city', 'state': 'State'}}
    

    然后您可以使用它来检索状态:

    s = set(r[key]['state'] for key in r)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-05
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      • 2017-01-05
      • 1970-01-01
      • 2023-04-06
      相关资源
      最近更新 更多