Python: how to convert a dictionary into a subscriptable array?

后端 未结 4 431
终归单人心
终归单人心 2020-12-09 15:52

I know how to convert a dictionary into an list in Python, but somehow when I try to get, say, the sum of the resulting list, I get the error \'dict_values\' object is

相关标签:
4条回答
  • 2020-12-09 16:12

    Yes, it did appear like a list on the older Python questions asked here. But as @Kasramvd said, assuming you are using python 3.X, dict.values is a dictionary view object. (Also, you definitely came up with this example hastily as you have four dictionary entries but want 10 list items, which is redundant.)

    0 讨论(0)
  • 2020-12-09 16:24

    @mgilson is right. A dictionary , by its intrinsic nature, isn't ordered.

    Still you can do this :

    alpha = {"A":1,"B":2,"C":3,"D":4,"E":5}   # dictionary
    my_list = []
    for key,value in alpha.items() :
        my_list.append(value)
    

    You can access your "values" from my_list, but it will not be in order.

    0 讨论(0)
  • 2020-12-09 16:25

    In python-3.X dict.values doesn't return a list like how it performs in python-2.X. In python-3.x it returns a dict-value object which is a set-like object and uses a hash table for storing its items. This feature, in addition to supporting most of set attributes, is very optimized for some operations like membership checking (using in operator). And because of that, it doesn't support indexing.

    If you want to get a list object, you need to convert it to list by passing the result to the list() function.

    the_values = dict.values()
    SUM = sum(list(the_values)[1:10])
    
    0 讨论(0)
  • 2020-12-09 16:32

    By assigning dict.values() to a list you are not converting it to a list; you are just storing it as dict_values (may be an object). To convert it write list=list(dict.values()). Now even while printing the list you will get the list elements and not dict_values(......).

    And as mentioned before don't use Python built-in names as your variable names; it may cause conflicts during execution and confusion while reading your code.

    0 讨论(0)
提交回复
热议问题