Skip to content
Advertisement

How to skip some results using double for loop?

I have a problem, so I made it simplified code, everything how it is here need to stay that way because of my bigger problem. I have 2 dictionaries and I have 2 for loops. I need to skip outputs with same result like AA, BB, CC etc… and I need to remove one of AB or BA, I need to keep AB, but I don’t need BA. Can you help me with this problem, but I need to keep it simple for my real problem?

one = {
    "A" : "A",
    "B" : "B",
    "C" : "C",
    "D" : "D",
    "E" : "E",
    "F" : "F",
    "G" : "G",
    "H" : "H"
}
two = {
    "A" : "A",
    "B" : "B",
    "C" : "C",
    "D" : "D",
    "E" : "E",
    "F" : "F",
    "G" : "G",
    "H" : "H"
}

for botname,bot in one.items():
    for topname, top in two.items():
            print (str(bot) + str(top))

Output:

AA*
AB
AC
AD
AE
AF
AG
AH
BA*
BB*
BC
BD
BE
BF
BG
BH
CA*
CB*
CC*
CD
CE
CF
CG
CH
DA*
DB*
DC*
DD*
DE
DF
DG
DH
EA*
EB*
EC*
ED*
EE*
EF
EG
EH
FA*
FB*
FC*
FD*
FE*
FF*
FG
FH
GA*
GB*
GC*
GD*
GE*
GF*
GG*
GH
HA*
HB*
HC*
HD*
HE*
HF*
HG*
HH*

‘*’ it’s not output, outputs with * I want to skip

Thanks in advance!

Advertisement

Answer

You can just keep the pairs where bot < top. This will discard the duplicates where top < bot, as well as the pairs where top == bot.

for bot in one.values():
    for top in two.values():
        if bot < top:
            print(bot + top)

There’s no need to use .items() if you’re only using the values, not the keys.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement