简体   繁体   English

如何将字符串读入词典列表?

[英]How do I read a string into a list of dictionaries?

I'm trying to turn a some strings into a list. 我正在尝试将一些字符串转换为列表。

I have have various strings called elementX, which I want to turn into a list with the same structure as Options. 我有各种称为elementX的字符串,我想将其转换为具有与Options相同结构的列表。

#turn string into list
element1 = {'label': '26', 'value': '26'}
element2 = {'label': '28', 'value': '28'}
element3 = {'label': '29', 'value': '29'}
type(element1)

options=[
        {'label': '26', 'value': '26'},
        {'label': '28', 'value': '28'},
        {'label': '29', 'value': '29'},
     ]

Goal is it to offer the labels of the string as Options in a Dropdown.dcc from Dash. 目标是在Dash的Dropdown.dcc中提供字符串的标签作为Options。

@zacha2, what is wrong with [element1, element2, element3] ? @ zacha2, [element1, element2, element3]什么问题?

Keep in mind that until 3.6 or 3.7, dictionaries are unordered so when you print them, the 'label' and 'value' tuples might be transposed but this doesn't affect the functionality of the dictionaries. 请记住,在3​​.6或3.7之前,字典是无序的,因此当您打印它们时,“标签”和“值”元组可能会转置,但这不会影响字典的功能。

Or do you have an arbitrary number of dictionaries called elementNNN and you want to collect them all at runtime? 还是您有任意数量的称为elementNNN的字典,并且想要在运行时收集它们? First I would reconsider your design so that you have instead something like elements[] instead. 首先,我将重新考虑您的设计,以便改为使用诸如elements[]类的东西。 But if you really need to do this for an arbitrary number of elementN variables, you can use: 但是,如果确实需要对任意数量的elementN变量执行此操作,则可以使用:

[v for (k,v) in locals().items if k.startswith('element')]

The locals() function will return a dictionary of local variables and their associated values. locals()函数将返回本地变量及其相关值的字典。

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

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