【问题标题】:Automatically Creating List of Dictionaries Based Upon Two Lists of Equal Length with Python用Python自动创建基于两个等长列表的字典列表
【发布时间】:2020-05-19 20:35:09
【问题描述】:

有两个列表:

customer_list = ["A7", "A8", "A9", "A10", "A11"] 
customer_index = ["8", "9", "10", "11", "12"]

目标是创建以下内容:

final_list = [
{
"kind": "report#variable",
"type": "A7",
"value": line[8]}
,
{
"kind": "report#variable",
"type": "A8",
"value": line[9]}
,
{
"kind": "report#variable",
"type": "A9",
"value": line[10]}
,
{
"kind": "report#variable",
"type": "A10",
"value": line[11]}
,
{
"kind": "report#variable",
"type": "A11",
"value": line[12]}
]

我尝试使用以下 Python 代码,但没有成功:

def create_final_list(list_1, list_2):
   new_list = []
   list_prefix = '{"kind": "report#variable",'
   for num in list_1:
      for val in list_2:
         list_1_num = ' "type": ' + num 
         list_2_val = ' "value": ' + val 
         new_list.append(list_prefix + list_1_num + list_2_val)
   return new_list

如上例所示,如何根据两个等长和所需格式的列表自动创建字典列表?

【问题讨论】:

  • 您不是在创建 JSON,而是在创建一个 dict 对象列表。
  • 不要尝试手动构造 JSON 字符串。先构造实际的对象(列表或字典),然后让Python内置的json模块生成字符串。
  • 您使用的是 Python 2 还是 Python 3? 它不起作用究竟是什么意思?

标签: python python-3.x pandas list python-2.7


【解决方案1】:

这不是 JSON;但是您在使用zip() 的列表理解中创建的字典列表:

customer_list = ["A7", "A8", "A9", "A10", "A11"] 
customer_index = ["8", "9", "10", "11", "12"]
line = [1,2,3,4,5,6,7,8,9,101,11,12,13,14]  # assume this `line` list

res = [{"kind": "report#variable", "type": x, "value": line[int(y)]} for x, y in zip(customer_list, customer_index)]

就像在 cmets 中一样,您可以这样做:

json.dumps(res)

..将res 转换为 JSON 字符串。

【讨论】:

  • 然后您可以简单地编写json.dumps(res) 将其转换为 JSON 字符串。
【解决方案2】:

由于 pandas 被标记,使用 dataframe 和 groupby 添加另一种方式:

df = pd.DataFrame({"kind": "report#variable","type":customer_list,"value":customer_index})
final = [g.droplevel(0).to_dict() for _,g in df.stack().groupby(level=0)]

[{'kind': 'report#variable', 'type': 'A7', 'value': '8'},
 {'kind': 'report#variable', 'type': 'A8', 'value': '9'},
 {'kind': 'report#variable', 'type': 'A9', 'value': '10'},
 {'kind': 'report#variable', 'type': 'A10', 'value': '11'},
 {'kind': 'report#variable', 'type': 'A11', 'value': '12'}]

【讨论】:

    【解决方案3】:

    试试

    lis = []
    for i in range(len(customer_index)):
        dic = {"type" : customer_list[i], "value" : customer_index[i]}
        lis.append(dic)
    

    这个输出

    [{'type': 'A7', 'value': '8'},
     {'type': 'A8', 'value': '9'},
     {'type': 'A9', 'value': '10'},
     {'type': 'A10', 'value': '11'},
     {'type': 'A11', 'value': '12'}]
    

    与您的代码一样,如果您想要line[8],请在字典初始化期间使用line[customer_index[i]] 而不是customer_index[i]。另外,根据您的要求,在字典中再添加 1 个 kind 键。

    上述代码仅在customer_listcustomer_index 长度相等时才有效,因为循环迭代n 次,其中n 是列表的相等长度。

    【讨论】:

      猜你喜欢
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      相关资源
      最近更新 更多