使用字典理解是否有更优雅的方法来实现相同的结果?
为了澄清,`
[
{
id: 11,
fields: {
staff: {
id: 6,
name: 'Jack'
},
attendance: 'some_date',
}
}
]
`
的格式始终为s
"foo 1=bar 2=bar"
答案 0 :(得分:1)
另一种方法:
s = "foo 1=bar 2=bar 3=rab"
#separate the upper level key from the rest
x = s.partition(" ")
#now create a dictionary from the lower level key/value pairs
res = {x[0]: dict(i.split("=") for i in x[2].split())}
print(res)
>>>{'foo': {'1': 'bar', '2': 'bar', '3': 'rab'}}
首先想一想,它可以作为词典理解来完成,但是列表不可用。
答案 1 :(得分:0)
您的方法意味着字符串将始终具有该形式,即具有单个键值对的dict
,其值为具有2个字符串键值对的另一个dict
。在这种情况下,我认为正则表达式是最直接的方式:
>>> s = "foo 1=bar 2=bar"
>>> import re
>>> pattern = r"(\w+)\s+(\w+)=(\w+)\s+(\w+)=(\w+)"
>>> K, k0, v0, k1, v1 = re.search(pattern, s).groups()
>>> {K:{k0:v0,k1:v1}}
{'foo': {'1': 'bar', '2': 'bar'}}
答案 2 :(得分:0)
您可以在Python3中使用带有正则表达式的递归来获得通用解决方案:
bottomNavigationView.setSelectedItemId(R.id.your_id);
测试:
import re
def get_dict(s):
if re.findall('^[a-zA-Z]+$', s[0]):
return {s[0]:get_dict(s[1:])}
return {s[0].split('=')[0]:s[0].split('=')[-1], **get_dict(s[1:])} if s[1:] else {s[0].split('=')[0]:s[0].split('=')[-1]}
输出:
list_of_strings = ['foo 1=bar 2=bar', 'foo bar 1=bar 2=bar']
new_data = [get_dict(i.split()) for i in list_of_strings]
答案 3 :(得分:0)
因为你想在这里使用理解是一种更优雅的方式。
它假设你的字符串有一个键(称为foo)和该键的许多键/值对
你可以为内部字典提供n个键值对
s = "foo 1=bar 2=bar 3=bar"
key_value_list = [ item for item in s.split() if '=' in item]
output_dict = {word:{item.split('=')[0]:item.split('=')[1] for item in key_value_list } for word in s.split() if '=' not in word}
print output_dict
输出: {' foo':{' 1':' bar',' 3':' bar',' ; 2':' bar'}}
第一个是列表理解,它创建了一个包含' =' 。这将用于生成内部字典
第二个是嵌套的字典理解,外部字典理解创建一个带有键的字典=没有' ='
上述键(即foo)的值是一个字典,它是通过在#1