How do I get the key of an item when doing a FOR loop through a dictionary or list in Python?

I am new to Python.

Say I have a list:

list = ['A','B','C','D']

The key for each item respectively here is 0,1,2,3 - right?

Now I am going to loop through it with a for loop...

for item in list:
    print item

That's great, I can print out my list.

How do I get the key here? For example being able to do:

print key
print item

on each loop?

If this isn't possible with a list, where keys are not declared myself, is it possible with a Dictionary?


Asked by: Dainton915 | Posted: 27-01-2022

Answer 1

The answer is different for lists and dicts.

A list has no key. Each item will have an index. You can enumerate a list like this:

>>> l = ['A','B','C','D']
>>> for index, item in enumerate(l):
...     print index
...     print item

I used your example here, but called the list 'l', to avoid a clash with a reserved word.

If you iterate over a dict, you are handed the key:

>>> d = {0: 'apple', 1: 'banana', 2: 'cherry', 3: 'damson', }
>>> for k in d:
...     print k
...     print d[k]

Answered by: Audrey888 | Posted: 28-02-2022

Answer 2

You want the index, not the key. For this you can use enumerate:

for index, item in enumerate(l):
    print index
    print item

This is mentioned in the section Looping Techniques in the Python tutorial which also covers looping over dictionaries while getting both the key and the value.

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v
gallahad the pure
robin the brave

Answered by: Owen895 | Posted: 28-02-2022

Answer 3

You should use a dictionary, anyway you could do something like:

for index, item in enumerate(yourlist):
    print "index:%d item:%s" % (index, item)

Answered by: Patrick897 | Posted: 28-02-2022

Similar questions

python - List a dictionary

In a list appending is possible. But how I achieve appending in dictionary? Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT|00000004| |.data __ctype_tab |00000000| r | OBJECT|00000101| |.rodata Symbols from _ashldi3.o: Name Value Class ...

python - Make Dictionary From 2 List

This question already has answers here:

Make dictionary from list with python

This question already has answers here:

python - how do i map to a dictionary rather than a list?

i have the following function, which doe a basic job of mapping an lxml object to a dictionary... from lxml import etree tree = etree.parse('file.xml') root = tree.getroot() def xml_to_dict(el): d={} if el.text: print '***write tag as string' d[el.tag] = el.text else: d[el.tag] = {} children = el.getchildren() if children: d[el.tag] = map(xml_to_dict, c...

list - How to get the key from a given name in dictionary in python

I have a variable called anime_dict which contains a dictionary of lists of objects as shown below.{'JI2212': ('Inu Yasha', [('year', 1992), ('rating', 3)]), 'EH389J': (Naruto', [('year', 1994), ('rating', 4), ('readers', 3424322)]), 'PPP67': ('Fruits Basket', [('Year', 1999), ('rating', 5), ('readers', 434232), ('chap', 40)])} so the key of the dict is the 1st part ('JI2212' for Inu Yasha), t...

Python Dictionary List

originally I had my program like so: inst = {} class IContainer: dicList = {} for i in range(10): inst[i] = IContainer() def FindEnd(node): if node.text != None: inst[counter].dicList[node.tag] = node.text else: for subNode in node: FindEnd(subNode) counter = 0 for element in root: if element.tag == "Items": for subE in element: if ...

python - A list as a key for a dictionary

I have multiple lists of tuples eg [([1, 2, 3, 4], 2), ([5, 6, 7], 3)] that I would like to have as keys to a dictionary (so each key in my dictionary would be a list of tuples). Unfortunately, according to the TypeError I'm getting (unhashable type: list), it seems that python doesn't like hashing lists. All of the elements in my list of tuples are ints ...

Dictionary out of list in python

How can I create a dictionary out of the a in python? If I have a list like this: a = ["Albert Einstein", "Nils Bohr"] And I want it to become this: b = {'Albert Eienstein': ['Albert', 'Eienstein'], 'Neils Bohr': ['Neils', 'Bohr']}

python - How to make dictionary from list

My list: list = ['name1', 'option1.1 value1.1', 'option1.2 value1.2', 'name2', 'option2.1 value2.1', 'option2.2 value2.2', 'option2.3 value2.3'] And i want create dictionary like this: dict = {'name1':{'option1.1':'value1.1', 'option1.2':'value1.2'}, 'name2':{'option2.1': 'value2.1', 'option2.2':'value2.2', 'option2.3':'value2.3'} I don't know how big is m...

python - How do I make a list with the same name as a dictionary key?

I have a dictionary, containing several hundred entries, of format: >>>dict {'1620': 'aaaaaa'} I would like to make new empty lists named '1620', etc. I have tried variations of the following but it doesn't recognize eachkey as a variable to be used when creating the list. Instead, it names the list literally "eachkey" and my key, in this example '1620', is not connected to the ne...

python - Dictionary or list?

I need to be able to store data, one being a number and one being the number of times it appeared. I have a for loop that calls a method that returns a dictionary: for x in range(total_holidays): t = trial() y = y + "\n" + str(x+1) + "," + str(t["brown"]) + "," + str(t["rainbow"]) + "," + str(t["nothing"]) + "," + str(t["days"]) total += t["days"] #print total if x%10000 == 0: y0...

python - How do I make a list a key value in a dictionary?

I need to make a dictionary where you can reference [[1,2],[3,4]] --> ([1,2]:0, [2,3]:0) I've tried different ways but I can't use a list in a dictionary. So i tried using tuples, but its still the same. Any help is appreciated!

python - given a list of value, and a list of key, How can I make a dictionary from both list?

This question already has answers here:

python - dictionary that contains list

I have a function that returns the following dictionary abc= {"type":"insecure","id":"1", "name":"peter","s_count":"2", "b_count":"1", "s_1_name":"melisa", "s_1_id":"2","s_2_name":"graham", "s_2_id":"4", "b_1_name":"henrik", "b_1_id": "9"} I want to chage the dictionary in the following way: xyz={"type":"insecure","id":"1", "name":"p...

python - Map list to dictionary according to value from other list

I have this list: [0,0,3,3,0,1,1,1,3,3,0,2,0,2,0,0,2,2] and this list: [18,23,56,34,23,67,89,43,12,22,34,21,54,23,67,12,45,67] (their lengths are the same)..I'd like to find a way to generate a dictionary from these lists by using as keys of the dict the values from the first list and as the values of each key the numbers of the second list corresponding t...

dictionary and list in python

I am working on my project in language computing. My list is list=["ഒരിടത്ത്‌","PR_PRP_S_NU","ചിക്കു","N_NST","എന്ന്","CC_CCD","പേരുള്ള","N_NN","ഒരു", "QT_QTF","പട്ടികൂട്ടി","N_NN","ഉണ്ട്","V_VAUX","ആയിരുന്നു","V_VM_VF",".","RD_PUNC"] I want to store these values into a dictionary in the same order in list like dict{"ഒരിടത്ത്‌":"PR_PRP_S_NU","ചിക്കു":"N_NST","എന്ന്":"CC_...

list - How to get the first value in a Python dictionary

I have a dictionary like this: myDict = { 'BigMeadow2_U4': (1609.32, 22076.38, 3.98), 'MooseRun': (57813.48, 750187.72, 231.25), 'Hwy14_2': (991.31, 21536.80, 6.47) } How can I get the first value of each item in my dicitionary? I want in the end a list: myList = [1609.32,57813.48,991.31]

Python - "map" a list of keys to a dictionary

I have a multidimensional dictionary in Python, and I have a list which has the keys that I want to access. What is the easiest way to get the value from the dictionary? Example: main = { 'one': { 'two': { 'three': "Final word" } } } mylist = ['one', 'two', 'three'] # and I want to print out the value of `three` ("Final word")

Dictionary out of a list in python

I want to create a dictionary out of a list that has several similar elements. But, in the dictionary, all these similar elements must have the same key. d_dict={} lst=['A1','A2','A3','2e','2o','2m'] for element in lst: if element.startswith('A'): d_dict[1].append(element) elif element.startswith('2'): d_dict[2].append(element) print(d_dict) My output should ...

python - How to sort a list as a value in a dictionary by the first value in each list?

I have a table of which I want to take 3 of the columns, the section name, its start and its end. The code I am using for this is: Contigs = {} with open('ecoli.gtf', 'rb') as csvfile: # Opens file reader = csv.reader(csvfile, dialect=csv.excel_tab) for row in reader: #Iterates through each row if row[0] in Contigs: # Checks if chromosome or contigs id is already in the dict or not and then ...

python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.

python, dictionary and int error

I have a very frustrating python problem. In this code fixedKeyStringInAVar = "SomeKey" def myFunc(a, b): global sleepTime global fixedKeyStringInAVar varMe=int("15") sleepTime[fixedKeyStringInAVar] = varMe*60*1000 #more code Now this works. BUT sometimes when I run this function I get TypeError: 'int' object does not support item assignment

python - Best way to create a NumPy array from a dictionary?

I'm just starting with NumPy so I may be missing some core concepts... What's the best way to create a NumPy array from a dictionary whose values are lists? Something like this: d = { 1: [10,20,30] , 2: [50,60], 3: [100,200,300,400,500] } Should turn into something like: data = [ [10,20,30,?,?], [50,60,?,?,?], [100,200,300,400,500] ] ...

python - List a dictionary

In a list appending is possible. But how I achieve appending in dictionary? Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT|00000004| |.data __ctype_tab |00000000| r | OBJECT|00000101| |.rodata Symbols from _ashldi3.o: Name Value Class ...

python - How to filter a dictionary by value?

Newbie question here, so please bear with me. Let's say I have a dictionary looking like this: a = {"2323232838": ("first/dir", "hello.txt"), "2323221383": ("second/dir", "foo.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt"), "324234324": ("third/dir", "dog.txt")} I want all values that are equal to each other to be moved into...

Python and dictionary like object

I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary). But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using isinstance and type (because they are considered b...

python - Remove dictionary from list

If I have a list of dictionaries, say: [{'id': 1, 'name': 'paul'}, {'id': 2, 'name': 'john'}] and I would like to remove the dictionary with id of 2 (or name 'john'), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).

C# way to mimic Python Dictionary Syntax

Is there a good way in C# to mimic the following python syntax: mydict = {} mydict["bc"] = {} mydict["bc"]["de"] = "123"; # &lt;-- This line mydict["te"] = "5"; # &lt;-- While also allowing this line In other words, I'd like something with [] style access that can return either another dictionary or a string type, depending on how it has been set. I've been trying to work...

python - Can a dictionary be passed to django models on create?

Is it possible to do something similar to this with a list, dictionary or something else? data_dict = { 'title' : 'awesome title', 'body' : 'great body of text', } Model.objects.create(data_dict) Even better if I can extend it: Model.objects.create(data_dict, extra='hello', extra2='world')

python - Make Dictionary From 2 List

This question already has answers here:

sorting - In Python, how can you easily retrieve sorted items from a dictionary?

Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key? For example, you had this: d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}

Python dictionary from an object's fields

Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: &gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } NOTE: It should not include methods. Only fields.

python - How do you retrieve items from a dictionary in the order that they're inserted?

Is it possible to retrieve items from a Python dictionary in the order that they were inserted?

python - How can I make a dictionary from separate lists of keys and values?

I want to combine these: keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] Into a single dictionary: {'name': 'Monty', 'age': 42, 'food': 'spam'}

python - Dictionary or If statements, Jython

I am writing a script at the moment that will grab certain information from HTML using dom4j. Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below: if type == 'extractTitle': extractTitle(dom) if type == 'extractMetaTags': extractMetaTags(dom)

Is a Python dictionary an example of a hash table?

One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?

python - Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?

The list sort() method is a modifier function that returns None. So if I want to iterate through all of the keys in a dictionary I cannot do: for k in somedictionary.keys().sort(): dosomething() Instead, I must: keys = somedictionary.keys() keys.sort() for k in keys: dosomething() Is there a pretty way to iterate t...

python - Interface to versioned dictionary

I have an versioned document store which I want to access through an dict like interface. Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int). from UserDict import DictMixin class VDict(DictMixin): def __getitem__(self, key): if isinstance(key, tuple): docid, rev = key e...

python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.

python - Check if a given key already exists in a dictionary and increment it

How do I find out if a key in a dictionary has already been set to a non-None value? I want to increment the value if there's already one there, or set it to 1 otherwise: my_dict = {} if my_dict[key] is not None: my_dict[key] = 1 else: my_dict[key] += 1

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python