2

Consider dictionaries like:

a_dict = {"a":1,"b":2,"c":3}
b_dict = {"A":5,"B":6,"C":7}
for (k,v),(k1,v1) in zip(a_dict.items(),b_dict.items())):  
    print(k,v);
    print(k1,v1);

output

b 2
B 6
a 1
A 5
c 3
C 7

After searching about dictionary i got that the elements of dictionaries are not sorted that's why these elements of dictionaries are printed randomly. But i want them printed sequentially. that is

a 1
A 5
b 2
B 6
c 3
C 7

How can I do that?

sazid008
  • 175
  • 2
  • 14
  • It depends on how you want them sorted. The answer using `chain` below sorts *all* the element by the lowercase version of the key (which may be what you want). – Jared Goguen Jan 22 '16 at 19:05

4 Answers4

1

You can use chaining and sorting:

from itertools import chain

a_dict = {"a":1,"b":2,"c":3}
b_dict = {"A":5,"B":6,"C":7}

for key, value in sorted(chain(a_dict.items(), b_dict.items()), 
                         key=lambda x: x[0].lower()):
    print(key, value)

Prints:

a 1
A 5
b 2
B 6
c 3
C 7
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

You can make order for both dicts with sorted(), like this:

a_dict = {"a": 1,"b": 2,"c": 3}
b_dict = {"A": 5,"B": 6,"C": 7}
for (k,v), (k1,v1) in zip(sorted(a_dict.items()), sorted(b_dict.items())):
    print(k,v)
    print(k1,v1)

Output:

a 1
A 5
b 2
B 6
c 3
C 7
George Petrov
  • 2,729
  • 1
  • 13
  • 20
1

If you want to retrieve data as you stored, you have to use OrderedDict since dictionaries doesn't keep data as it is inserted.

from collections import OrderedDict

a_dict=OrderedDict((k, v) for k,v in [["a",1],["b",2],["c",3]])
b_dict=OrderedDict((k, v) for k,v in [["A",5],["B",6],["C",7]])

for (k,v),(k1,v1) in zip(a_dict.items(),b_dict.items()):
    print(k,v);
    print(k1,v1);
TRiNE
  • 5,020
  • 1
  • 29
  • 42
0

To avoid repeated sorting you can also use OrderedDict from collections module.

Naihonn
  • 1
  • 1