-3

If I want to get a bot with an ID, which is faster between:

storage = {
    'bots': [
        { 'id': 123, 'auth': '81792367' },
        { 'id': 345, 'auth': '86908472' },
        { 'id': 543, 'auth': '12343321' }
    ]
}

id = 345
bot = next(bot['auth'] for bot in storage['bots'] if bot['id'] == id)

and

storage = {
    'bots': {
        123: '81792367',
        345: '86908472',
        543: '12343321',
    }
}

id = 345
bot = storage['bots'][id]

and which must be used for the Python pep8 or most beautiful?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • If you want to know what is faster in your particular circumstances, then **try it**. If you have a question about style, that is off topic here. – Karl Knechtel Nov 19 '22 at 16:21
  • Do a bit of research using the `timeit` module or the iPython magic function `%timeit`. – S3DEV Nov 19 '22 at 16:22

1 Answers1

2

Bear in mind that the time complexity of lookup (i.e using the in keyword) for a list is O(n) whereas, the same operation has a time complexity of O(1) for a dictionary (Time Complexity of Collection Ops)

Meanwhile the Time Complexity of Get Item is same (O(1)) for both. So, I would say you're better off with the second approach.

Seyi Daniel
  • 2,259
  • 2
  • 8
  • 18