[英]How to iterate values inside dictionary of lists in PYTHON
I have a complicated method that needs to work correctly, that I can't seem to figure out why it doesn't.我有一个需要正常工作的复杂方法,但我似乎无法弄清楚为什么它不能正常工作。
I have a dictionary as it follows:我有一本字典如下:
{'view': ['premium_subscribers', 'premium_content'], 'delete': ['admins', 'normal_content', 'premium_content']}
I need to know how to iterate one by one through each specific key values, which are arrays.我需要知道如何通过每个特定的键值(数组)一一迭代。 For example:
例如:
key = delete
for loop (that iterates 1 by 1 through key "delete's" values
takes "admins" value and does some processing
in the next iteration takes normal_content and does same processing
and so on ......
its basically checking for a match to be found.
In case if you're interested in my method, I have it below.如果你对我的方法感兴趣,我在下面。 It has 3 dictionaries and is comparing their key's values to accomplish access permission.
它有 3 个字典,并且正在比较它们的键值以完成访问权限。
If the for loop iterates correctly through each value of that key, it will start working as expected.如果 for 循环正确地遍历该键的每个值,它将按预期开始工作。
def accessPermission(operation, user, object):
domains = dict()
types = dict()
access = dict()
access = json.load(open("access.txt"))
domains = json.load(open("domains.txt"))
types = json.load(open("types.txt"))
print(types)
print(access)
print(domains)
if operation in access.keys():
firstkeyvalue = access.get(operation)[0]
if firstkeyvalue in domains.keys():
if user in domains.get(firstkeyvalue):
for access.get(operation)[0] in access:
if object in types.values():
print("Success")
else:
print("Error: access denied")
else:
print("Error: access denied")
else:
print("Error: access denied")
else:
print("Error: access denied")
Seems you only need to iterate through the elements like this:似乎您只需要遍历这样的元素:
dict = {'view': ['premium_subscribers', 'premium_content'], 'delete': ['admins', 'normal_content', 'premium_content']}
key = 'delete' #set somewhere
for v in dict[key]:
print(v)
#do what you need with that
Output:输出:
admins
normal_content
premium_content
Each Value is a list
, so you need an extra loop
for iterating over the items of each list:每个 Value 都是一个
list
,因此您需要一个额外的loop
来迭代每个列表的项目:
data_dict = {'view': ['premium_subscribers', 'premium_content'], 'delete': ['admins', 'normal_content', 'premium_content']}
for key in data_dict:
values = data_dict[key]
# iterate over list of values
for v in values:
# Now you have access to each one
print(v)
Output:输出:
premium_subscribers
premium_content
admins
normal_content
premium_content
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.