简体   繁体   English

python字典,其值具有多个参数

[英]python dictionary with value having multiple parameters

i have a problem in fetching values from a dictionary. 我在从字典中获取值时遇到问题。 di is a dictionary. di是字典。

for key in di.keys()
    print("key is = %s" %key)
for value in di.values()
    print("value is = %s" %value)

it gives output as 它给出的输出为

key is = 1

and

value is = xyz=0 | pqr=70 | abc=300

i want all 3 values(0,70,300) above in separate variables. 我想要上面所有3个值(0,70,300)在单独的变量中。 i am not able to do 我做不到

di['xyz']

since xyz is itself in a value. 因为xyz本身就是一个值。 how to fetch all these values? 如何获取所有这些值? is it a nested dictionary? 它是一本嵌套词典吗?

From the looks of it, this is your dictionary 从外观上看,这是您的字典

>>> di = {'1': 'xyz=0 | pqr=70 | abc=300'}

Or maybe {1: 'xyz=0 | pqr=70 | abc=300'} 或者,也许{1: 'xyz=0 | pqr=70 | abc=300'} {1: 'xyz=0 | pqr=70 | abc=300'} {1: 'xyz=0 | pqr=70 | abc=300'} , but you weren't very clear in the question so I'll assume the first. {1: 'xyz=0 | pqr=70 | abc=300'} ,但是您在问题中不太清楚,所以我假设第一个。

It's weird that you would have this as a dictionary, so I won't bother trying to think about why that may be, instead I'll just show you how you could build what you want from the string 'xyz=0 | pqr=70 | abc=300' 您将其作为字典很奇怪,所以我不会费心去想为什么会这样,相反,我只会向您展示如何使用字符串'xyz=0 | pqr=70 | abc=300'构建所需的内容'xyz=0 | pqr=70 | abc=300' 'xyz=0 | pqr=70 | abc=300'

>>> di['1'].split(' | ')
['xyz=0', 'pqr=70', 'abc=300']

Splits by the vertical bars 按竖线分割

>>> [x.split('=') for x in di['1'].split(' | ')]
[['xyz', '0'], ['pqr', '70'], ['abc', '300']]

Splits by equal signs to make key-pair lists 按等号拆分以创建密钥对列表

>>> dict(x.split('=') for x in di['1'].split(' | '))
{'xyz': '0', 'abc': '300', 'pqr': '70'}

Builds a dict out of that 建立一个dict出的那

>>> di = dict(x.split('=') for x in di['1'].split(' | '))
>>> di['xyz']
'0'

and now you can access it like di['xyz'] 现在您可以像di['xyz']一样访问它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM