1

random list args just not includes in mydict and disappear and i dont know what to do. my code -

def openOrSenior(data):
    data = dict(data)
    print(data)
    output = []
    for k, v in data.items():
        if k >= 55 and v > 7:
            output += ['Senior']
        else:
            output += ['Open']
    return output
print(openOrSenior( [[17, 18], [57, 25], [56, 24], [41, 2], [22, 27], [48, 15], [39, 21], [41, 2]] ))

output-

{17: 18, 57: 25, 56: 24, 41: 2, 22: 27, 48: 15, 39: 21}
['Open', 'Senior', 'Senior', 'Open', 'Open', 'Open', 'Open']

where is [41, 2]? it happens sometimes with diferent numbers and places in list, so i can't understand where is the problem. I need it for this kata in codewars https://www.codewars.com/kata/5502c9e7b3216ec63c0001aa/train/python

LowerHouse
  • 15
  • 4
  • Does this answer your question? [Is there a way to preserve duplicate keys in python dictionary](https://stackoverflow.com/questions/11141383/is-there-a-way-to-preserve-duplicate-keys-in-python-dictionary) ... there are others searching with variations of `python dict duplicate key` – wwii Mar 28 '20 at 23:03

2 Answers2

2

k = 41 (4th item) was already in this list... Python dictionaries don't support duplicate keys and it considers the last occurrence of k = 41 which is [41, 2].

Chicodelarose
  • 827
  • 7
  • 22
1

keys in a dict are unique, so you are overwriting the key 41 shrinking the expected output, to fix you can use:

def openOrSenior(data):
    output = []
    for k, v in data:
        if k >= 55 and v > 7:
            output += ['Senior']
        else:
            output += ['Open']
    return output
print(openOrSenior( [[17, 18], [57, 25], [56, 24], [41, 2], [22, 27], [48, 15], [39, 21], [41, 2]] ))

output:

['Open', 'Senior', 'Senior', 'Open', 'Open', 'Open', 'Open', 'Open']

as you can see the inner lists are unpacked in 2 variables, k and v


or you can use a list comprehension:

def openOrSenior(data):
    return ['Senior' if k>=55 and v>=6 else 'Open' for k, v in data]
kederrac
  • 16,819
  • 6
  • 32
  • 55