JavaEar 专注于收集分享传播有价值的技术资料

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

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 not subscriptable. Also, I plan to sum only several items in the list.

dict={A:1, B:2, C:3, D:4}
list=dict.values()
SUM=sum(list[1:3])

Upon closer inspection, I noticed that when the resulting list is printed out, it always gives dict_values(......) as the output which I can't remove. How do I get around this?

4个回答

    最佳答案
  1. By assigning dict.values() to list u are not converting it to list u are just storing it as dict_values (may be an object). To convert write list=list(dict.values()). Now even while printing the list u 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 confusions while reading your code.

  2. 参考答案2
  3. In python-3.X dict.values doesn't return a list like as 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 of supporting the most set attributes, it's so 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 passing the result to the list() function.

    values = dict.values()
    SUM = sum(list(values)[1:10])
    

    Also don't use python built-in names as your variable names.

  4. 参考答案3
  5. 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.)

  6. 参考答案4
  7. @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.