1

I am using session in my Django Application.

request.session['permissions'] is structured in the following manner. The key is same for every values. Basically it is a list of dictionaries

[{'mykey': 'value1'}, {'mykey': 'value2'}, {'mykey': 'value3'}, 
 {'mykey': 'value4'}, {'mykey': 'value5'}, {'mykey': 'value6'}]

permissions = request.session['permissions']

Now I want to check if value4 is present inside permissions. I am not getting how to check the value.

Whenever I am trying to access value like this

permissions.mykey

It is giving me error

'list' object has no attribute 'mykey'

I want to do similar like this

permissions = request.session['permissions']
if value not in permissions:
   print('Value is inside list')
Georgy
  • 12,464
  • 7
  • 65
  • 73
Cipher
  • 2,060
  • 3
  • 30
  • 58

4 Answers4

3

use a for loop to get the single dictionary and then check the key

for perm in permissions: 
    if value in perm.values():
        print('Value is inside list')
Exprator
  • 26,992
  • 6
  • 47
  • 59
2

I think you can do it like this using filter:

permissions = request.session['permissions']
exists = list(filter(lambda x: x.get('mykey') == 'value4', permissions))  # for python 3

# for python2
#  exists = filter(lambda x: x.get('mykey') == 'value4', permissions)

if len(exists) > 0:
   print('value4 exists')
ruddra
  • 50,746
  • 7
  • 78
  • 101
0
value_to_check = some_value
permissions = request.session['permissions']
for perm in permissions:
    for key in perm:
        if perm[key] == value_to_check:
           print "Value is present"
Pranitha
  • 1
  • 1
  • 1
0

As the other answers point out. The issue is that you are trying to use a dictionary accessor on a list object. Since permissions is a list of dictionaries you need to check all the dictionaries in the list for the value4. This can be done in many ways, in my mind the most pythonic way would be to use list comprehension, something like [value4 == d for d['mykey'] in permissions]

ClimbingTheCurve
  • 323
  • 2
  • 14