-1

I am very new to python and can't figure out how to do something like this:

r = {a:a, b:8}
p = {a:b, b:1}


    for item in r and p:
        var1 = item['a']
        var2 = user_item['b']
        ... do some stuff

(includes both dictionaries r and p instead of "for item in r:" which only includes one dict r)

I want to basically iterate through all items in two different dictionaries. Would I need two loops? One for r going through and one for p going through?

John Down
  • 490
  • 2
  • 5
  • 20
  • Those are `dict`'s; do you want to iterate over the keys or the values? – Cyphase Aug 26 '15 at 05:35
  • 2
    Your code is invalid. Please post some real code, and clarify what kind of thing you want to do with the items of the dicts. – juanchopanza Aug 26 '15 at 05:36
  • 2
    @SeanM looks like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. You should tell us what you really want, like what you expect your output to be. – Anand S Kumar Aug 26 '15 at 05:43
  • Also, you should clean up the question. The title says lists, the body says dictionaries, and the indentation is bad. – Cyphase Aug 26 '15 at 05:45
  • I think it's important to note here that dictionaries are ordered [quite arbitrarily](http://stackoverflow.com/questions/526125/why-is-python-ordering-my-dictionary-like-so), so using first item in both of them for any sort of comparison may not return the result you are expecting. – Arthur.V Aug 26 '15 at 06:03

1 Answers1

2

This will do what you want:

import itertools

for item in itertools.chain(r, p):
    do_some_stuff(item)

itertools.chain takes an arbitrary number of iterables and returns an iterator that will iterate over all the items in each iterable, in the order the iterables are given.

Note that in your case, r and p are dictionaries, so by default iterating over them will iterate over the keys, not the values.

Cyphase
  • 11,502
  • 2
  • 31
  • 32
  • If I understand correctly: This will ask like a outer for loop would and out r through loop and then p? – John Down Aug 26 '15 at 05:40
  • @SeanM, soort of. I wouldn't describe it as "like an outer for loop", but it would be equivalent in your case, yes. – Cyphase Aug 26 '15 at 05:42