Python Forum
Why list(dict.keys()) does not work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why list(dict.keys()) does not work?
#1
dict={'a':'aaa','b':'bbb','c':'ccc'}

list(dict.keys())
Quote:TypeError                                 Traceback (most recent call last)
<ipython-input-60-be97bb392967> in <module>()
----> 1 list(dict.keys())

TypeError: 'list' object is not callable


I want to get a list of the keys of a dictionary for further manipulation. But don't know why this does not work. Somebody here:http://stackoverflow.com/questions/17322...t-indexing
suggested they can do by this way, but it does not work for me.

Another question is: Can I access dictionary by index instead of key?

Thanks,

L
Reply
#2
Hello!
First, do not use keywords as variable names. I mean dict.

You can call list() built-in in the interpreter but in a script, you have to assign list() returns to a variable or use it as a callback.

The interpreter:
In [1]: dict={'a':'aaa','b':'bbb','c':'ccc'}

In [2]: list(dict.keys())
Out[2]: ['b', 'a', 'c']
In script:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

my_dict = {'a':'aaa','b':'bbb','c':'ccc'}

l = list(my_dict.keys())

print(l)
print(my_dict.keys())
Output:
Output:
['a', 'c', 'b'] ['a', 'c', 'b']
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
(Feb-02-2017, 07:19 AM)landlord1984 Wrote:
dict={'a':'aaa','b':'bbb','c':'ccc'}

list(dict.keys())
Quote:TypeError                                 Traceback (most recent call last)
<ipython-input-60-be97bb392967> in <module>()
----> 1 list(dict.keys())

TypeError: 'list' object is not callable


I want to get a list of the keys of a dictionary for further manipulation. But don't know why this does not work. Somebody here:http://stackoverflow.com/questions/17322...t-indexing
suggested they can do by this way, but it does not work for me.

Another question is: Can I access dictionary by index instead of key?

Thanks,

L

That should work. Since you use dict which is a type name as a variable, I can assume that you have a list variable elwhere in your code, that hides the list() function.

No, you cannot access a dictionary by index. You can at best access the keys by index and then use the keys to access the values. But the key order can change if you add something to the dictionary.
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#4
(Feb-02-2017, 07:55 AM)wavic Wrote: my_dict = {'a':'aaa','b':'bbb','c':'ccc'}

l = list(my_dict.keys())

print(l)
print(my_dict.keys())

Weird....The script code works. But those in console still does not return "TypeError: 'list' object is not callable". Anyway, I am writing in a script, jsut sometimes do quick testing in console

(Feb-02-2017, 10:06 AM)Ofnuts Wrote:
(Feb-02-2017, 07:19 AM)landlord1984 Wrote:
dict={'a':'aaa','b':'bbb','c':'ccc'} list(dict.keys())
Quote: TypeError Traceback (most recent call last) <ipython-input-60-be97bb392967> in <module>() ----> 1 list(dict.keys()) TypeError: 'list' object is not callable
I want to get a list of the keys of a dictionary for further manipulation. But don't know why this does not work. Somebody here:http://stackoverflow.com/questions/17322...t-indexing suggested they can do by this way, but it does not work for me. Another question is: Can I access dictionary by index instead of key? Thanks, L
That should work. Since you use dict which is a type name as a variable, I can assume that you have a list variable elwhere in your code, that hides the list() function. No, you cannot access a dictionary by index. You can at best access the keys by index and then use the keys to access the values. But the key order can change if you add something to the dictionary.

Ok. I see. I think a need to give up using dictionary in this case. I want to do some manipulation of insert and remove.
Reply
#5
Quote:But the key order can change if you add something to the dictionary.
Before 3.6 this is true,but not after Cry 
Quote:Another question is: Can I access dictionary by index instead of key?
It can work with 3.6,but if you should do it is an other case Think
>>> d = {'a':'aaa','b':'bbb','c':'ccc'}
>>> d
{'a': 'aaa', 'b': 'bbb', 'c': 'ccc'}

>>> lst = list(d.keys())
>>> lst
['a', 'b', 'c']

# Index will match dict because in 3.6 are dict ordered 
>>> d[lst[2]]
'ccc'

# Add something and the order do not change
>>> d['d'] = 'ddd'
>>> d
{'a': 'aaa', 'b': 'bbb', 'c': 'ccc', 'd': 'ddd'}

>>> d.update({'e': 'eee'})
>>> d
{'a': 'aaa', 'b': 'bbb', 'c': 'ccc', 'd': 'ddd', 'e': 'eee'}
Reply
#6
A less elegant solution using nested dict that can be used with any python version:

item_dict = {
    '1': {
        'Item': 'Widgets',
        'Unit': 'each',
        'QtyPerUnit': 1,
        'PricePerUnit': 14.25
    },
    '2': {
        'Item': 'Wigs',
        'Color': ['red', 'brown', 'white'],
        'Unit': 'each',
        'QtyPerUnit': 1,
        'PricePerUnit': 5.25
    },
    '3': {
        'Item': 'fountain drink',
        'Size': ['small', 'medium', 'large'],
        'Unit': 'Ounces',
        'QtyPerUnit': 16,
        'PricePerUnit': 1.95
    }
}

merchandise = list(item_dict.keys())
merchandise.sort()
print('merchandise: {}'.format(merchandise))
print('item_dict 1: {}'.format(item_dict['1']))
results:
Output:
merchandise: ['1', '2', '3'] item_dict 1: {'PricePerUnit': 14.25, 'Item': 'Widgets', 'QtyPerUnit': 1, 'Unit': 'each'}
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,319 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Beginner: Code not work when longer list raiviscoding 2 815 May-19-2023, 11:19 AM
Last Post: deanhystad
  How to work with list kafka_trial 8 2,001 Jan-24-2023, 01:30 PM
Last Post: jefsummers
  Membership test for an element in a list that is a dict value for a particular key? Mark17 2 1,203 Jul-01-2022, 10:52 PM
Last Post: Pedroski55
  Are list/dict comprehensions interpreted really sequentially? anata2047 3 1,450 May-31-2022, 08:43 PM
Last Post: Gribouillis
  Updating nested dict list keys tbaror 2 1,274 Feb-09-2022, 09:37 AM
Last Post: tbaror
  Loop Dict with inconsistent Keys Personne 1 1,601 Feb-05-2022, 03:19 AM
Last Post: Larz60+
  Remove empty keys in a python list python_student 7 3,008 Jan-12-2022, 10:23 PM
Last Post: python_student
  Create Dict from multiple Lists with duplicate Keys rhat398 10 4,055 Jun-26-2021, 11:12 AM
Last Post: Larz60+
  Compile list of dictianories out of another list of dictianories by certain keys CatorCanulis 10 4,087 Jun-10-2021, 08:35 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020