【问题标题】:Get dictionary values as List获取字典值作为列表
【发布时间】:2018-09-28 09:22:30
【问题描述】:

我知道之前有人问过这个问题,但我尝试过但无济于事。

我有下面的字典,想转换成列表,转换成列表的最好方法是什么

dct = {'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}

dList = list(dct.values())

结果:

[['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']]

我需要拆分列表:

['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']

稍后,我想将“dList”中的项目列表与另一个列表进行比较。

【问题讨论】:

  • 在你的代码中追加这一行dlist = [i for i in dlist[0]]
  • 为什么不只是dList = dct['result']?
  • @trozen,工作感谢

标签: python python-3.x list dictionary dataframe


【解决方案1】:

如果您知道列表是与'result' 键关联的值,只需调用dct['result']。

>>> dct = {'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
>>> dct
{'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
>>> dct['result']
['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']

将值转换为列表是不必要的,效率低下,并且如果您的 dict 有超过 1 个 (key, value) 对,则可能返回错误的值。

【讨论】:

    【解决方案2】:

    你的字典只有一个值,它本身就是一个元素列表。所以只需调用result 键,您将获得列表值。

    如果您想要代码中的列表,请添加索引 [0] 之类的,

    dList = list(dct.values())[0]

    希望这会有所帮助!干杯!

    【讨论】:

    • 没有。如果您想要关联到“结果”的值,只需调用dct['result']。不要希望 dict 真的只有 1 个元素,或者它会在 Python 3.6 或更高版本中正确排序和使用。
    • @EricDuminil 我在第 1 行也提到过。
    猜你喜欢
    • 1970-01-01
    • 2022-12-01
    • 2011-11-25
    • 2012-03-03
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    相关资源
    最近更新 更多