1

I'm new to Python and I'm wondering how can I iterate over part of the keys in a list of dictionaries.

Suppose I have something like:

OrderedDict([('name', 'Anna'), ('AAA', '15'), ('BBB', '49'), ('CCC', '38')])
OrderedDict([('name', 'Bob'), ('AAA', '31'), ('BBB', '21'), ('CCC', '41')])
etc.

I need to retrieve and iterate over AAA, BBB, CCC (keys, not values), but:

  • only one time (not repeating for every dict in the list, but once, e.g. only for Anna)
  • skipping 'name', just those going after
  • in reality, I have many more of these keys (more than 10), so the question is how to iterate and not hard code it

I'd be very glad if you could help

Thanks a lot!

AMC
  • 2,642
  • 7
  • 13
  • 35
Sabie
  • 77
  • 1
  • 8
  • Do all the dicts have the same keys? – Barmar Jun 25 '20 at 23:27
  • I believe you will find the answers to [this question](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) quite useful. You will need to handle the breaking of the iteration and the skipping of certain keys in conditionals or some other manipulation, but that resource should get you started. – gallen Jun 25 '20 at 23:27
  • @gallen That doesn't really address the problem of multiple dicts in a list. – Barmar Jun 25 '20 at 23:28
  • Are all dictionaries going to have these keys? Why not just take the first element of your list of dictionaries and go through the keys ignoring `'name'`? – busybear Jun 25 '20 at 23:29
  • @Barmar Which is why it's a comment and not an answer ;). To handle multiple items in a list, iterate over your collection and have a break condition. – gallen Jun 25 '20 at 23:29
  • @Barmar yes, exactly the same. That's why it will be enough to iterate just once (or only for 1 dict in this list) – Sabie Jun 25 '20 at 23:31
  • 1
    Then just iterate over `list_of_dicts[0]`, and skip `name`. – Barmar Jun 25 '20 at 23:32
  • 1
    Does this answer your question? [Iterate over a dict except for x item items](https://stackoverflow.com/questions/36184371/iterate-over-a-dict-except-for-x-item-items) – busybear Jun 25 '20 at 23:38
  • Have you tried breaking down the problem, writing any pseudocode, etc. ? – AMC Jun 26 '20 at 01:51

5 Answers5

3

Just iterate over the first list, and check if it's name so you can skip it.

for key in list_of_dicts[0]:
    if key != 'name':
        print(key)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you very much! This is what's needed. And is there a way to print out specific key columns? Like, for instance, if I want to print out only keys from columns 4 and 5? – Sabie Jun 25 '20 at 23:43
  • "only one time (not repeating for every dict in the list, but once)" – Red Jun 25 '20 at 23:46
  • @Sabie What do you mean by key columns? What is your expected output? – Barmar Jun 25 '20 at 23:47
  • @Barmar maybe tuple would be a more correct word here, instead of column. Like the one with name will be 0, AAA - first, and suppose I've got a long list and need only specific keys from there, and I need key from tuple 4-5 for example – Sabie Jun 25 '20 at 23:55
  • 1
    `keys = list(list_of_dicts[0].keys())` then you can use `keys[4]`, `keys[5]`, etc. – Barmar Jun 26 '20 at 00:12
  • If you need something more robust than this (e.g. ensuring the first list contains all of the keys in use by all the other dicts), you can use [zip](https://docs.python.org/3.8/library/functions.html#zip), and double-check the length of the zipped list versus the length of each of the dicts. – jpaugh Apr 02 '21 at 19:23
1

You can extract the keys from the first row by using:

keys = (key for key in list_of_dicts[0] if key != 'name')

Now you can iterate through the keys using something like:

for var in keys:
    print(var)
Alterlife
  • 6,557
  • 7
  • 36
  • 49
1

I'm not sure if it's the best way, but I'd do it like this:

Dict = OrderedDict([('name', 'Anna'), ('AAA', '15'), ('BBB', '49'), ('CCC', '38')])
keys = [] # keys is an empty list

for i in Dict: # Iterate over all keys in the dictionary
    if i != 'name': # Exclude 'name' from the list
        keys.append(i) # Append each 'i' to the list

That will get you a list, keys, of each of the keys in Dict, excluding 'name'.
You can now iterate over the keys like this:

for i in keys:
    print(i) # Do something with each key

And if you want to iterate over the values as well:

for i in keys:
    print(Dict[i]) # Do something with each value
Rilazy
  • 88
  • 8
0

You would use a for loop. Here is an example (I called i since I do not know what you call the argument of that function):

 i = [('name', 'Anna'), ('AAA', '15'), ('BBB', '49'), ('CCC', '38')]
 for a in range(len(i)):
     print(i[a][1])

The above gets the index of a, and inside the tuple (which has 2 elements so 0 or 1) gets the 2nd index.

NOTE:

You might want to make a nested for loop to get the ideals within the tuple.

Red
  • 26,798
  • 7
  • 36
  • 58
0

Here is what you can do:

lst = [{...}, {...}, {...}, {...}, ...]

f = ['name']
for d in lst: # For every dict in the list
    for k in d: # For every key in the dict
        if k not in f: # If the key is not in the list f
            # Do something
            f.append(k) # Add that key to f so the program won't iterate through it again


UPDATE

(I just found out that every dict has the same keys, so there's no need to do all this checking):

lst = [{...}, {...}, {...}, {...}, ...]

for d in lst: # For every dict in the list
    for k in d: # For every key in the dict
        if k != 'name': # If the key is not 'name'
            # Do something
Red
  • 26,798
  • 7
  • 36
  • 58
  • 1
    This was my original answer (except I used a set rather than a list), but then she commented that every dict has the same keys, so there's no need to do all this checking. – Barmar Jun 25 '20 at 23:48