连接每个字典值中的字符串列表

2024-06-08 17:41:33 发布

您现在位置:Python中文网/ 问答频道 /正文

从包含产品线项目(嵌入MDX查询格式)和产品类别代码的Pandas dataframedf3pa中,我有一个字典uni3pa,其中产品类别代码Code作为字典keys,字符串列表Item(MDX格式)作为values

uni3pa = df3pa.groupby('Code')['Item'].apply(list).to_dict()

一小撮uni3pa

uni3pa = 
{'3PA SMARTPAY': ['[Item].[Item].[10006543 - Smartpay User Licence]',
'[Item].[Item].[10006544 - SmartPay User Licence per Site]'],
'3PA OTHER': ['[Item].[Item].[10001234 - 3rd Party App User Licence]', 
'[Item].[Item].[10001235 - 3rd Party App User Licence (min 3 per site]',
'[Item].[Item].[10001236 - 3rd Party Apps Single User]']}

我追求的最终结果是,使用'+'将每个key中的所有值连接起来,以生成一个可以使用的MDX查询,例如:

uni3pa['3PA OTHER'] = '[Item].[Item].[10001234 - 3rd Party App User 
Licence] + [Item].[Item].[10001235 - 3rd Party App User Licence (min 3 per site] + 
[Item].[Item].[10001236 - 3rd Party Apps Single User]'

使用this link(我使用了许多其他方法,但这是我能找到的对本期最有帮助的方法),我能够为每个产品分组创建数组,如下所示:

array = []
for el in [' + '.join(value) for key, value in uni3pa.items()]:
    array.append(el)

In [46]: array[2]
Out[46]: '[Item].[Item].[10001234 - 3rd Party App User Licence] + 
[Item].[Item].[10001235 - 3rd Party App User Licence (min 3 per site] + 
[Item].[Item].[10001236 - 3rd Party Apps Single User]'

#for clarity, array[2] is '3PA OTHER'

我在这里选择了数组,因为这是将所有组转换为所需格式的最简单方法。但是,有100个组,如果我能够通过组名(例如3PA OTHER而不是array[2]来识别它们,这将容易得多

在字典中必须有一种更简单的方法来实现这一点,这样我就可以调用uni3pa['3PA OTHER'],并且该值是所需的格式


Tags: 方法app字典party格式sitelicencemin
1条回答
网友
1楼 · 发布于 2024-06-08 17:41:33

这是通过将列表理解改为词典理解来实现的:

>>> uni3pa = {'3PA SMARTPAY': ['[Item].[Item].[10006543 - Smartpay User Licence]',
'[Item].[Item].[10006544 - SmartPay User Licence per Site]'],
'3PA OTHER': ['[Item].[Item].[10001234 - 3rd Party App User Licence]', 
'[Item].[Item].[10001235 - 3rd Party App User Licence (min 3 per site]',
'[Item].[Item].[10001236 - 3rd Party Apps Single User]']}

>>> {k: ' + '.join(v) for k, v in uni3pa.items()}
    {'3PA SMARTPAY': '[Item].[Item].[10006543 - Smartpay User Licence] + [Item].[Item].[10006544 - SmartPay User Licence per Site]',
     '3PA OTHER': '[Item].[Item].[10001234 - 3rd Party App User Licence] + [Item].[Item].[10001235 - 3rd Party App User Licence (min 3 per site] + [Item].[Item].[10001236 - 3rd Party Apps Single User]'}

相关问题 更多 >