Python – Unlist 单值字典列表
给定字典列表,执行取消列出我们只有 1 个字典作为记录元素的记录。
Input : test_list = [{‘best’: [{‘a’: 6}], ‘Gfg’: 15}]
Output : [{‘best’: {‘a’: 6}, ‘Gfg’: 15}]
Explanation : The value list associated with ‘best’ key is changed to dictionary.
Input : test_list = [{‘Gfg’: [{‘best’ : 17}]}]
Output : [{‘Gfg’: {‘best’: 17}}]
Explanation : ‘Gfg’ key’s value changed to single dictionary.
方法 #1:使用循环 + isinstance()
这是可以执行此任务的蛮力方式。在此,我们使用 isinstance() 测试列表类型,循环用于迭代。
Python3
# Python3 code to demonstrate working of
# Unlist Single Valued Dictionary List
# Using loop + isinstance()
# initializing list
test_list = [{'Gfg': 1,
'is': [{'a': 2, 'b': 3}]},
{'best': [{'c': 4, 'd': 5}],
'CS': 6}]
# printing original list
print("The original list is : " + str(test_list))
# Using loop + isinstance()
for dicts in test_list:
for key, val in dicts.items():
# isinstance() is used to check for list to convert
if isinstance(val, list):
dicts[key] = val[0]
# printing result
print("The converted Dictionary list : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Unlist Single Valued Dictionary List
# Using list comprehension + isinstance()
# initializing list
test_list = [{'Gfg': 1,
'is': [{'a': 2, 'b': 3}]},
{'best': [{'c': 4, 'd': 5}],
'CS': 6}]
# printing original list
print("The original list is : " + str(test_list))
# Using list comprehension + isinstance()
# Similar way as above, extracting first element of list
res = [{key: val[0] if isinstance(val, list) else val
for key, val in sub.items()}
for sub in test_list]
# printing result
print("The converted Dictionary list : " + str(res))
输出 :
The original list is : [{'Gfg': 1, 'is': [{'b': 3, 'a': 2}]}, {'CS': 6, 'best': [{'d': 5, 'c': 4}]}]
The converted Dictionary list : [{'Gfg': 1, 'is': {'b': 3, 'a': 2}}, {'CS': 6, 'best': {'d': 5, 'c': 4}}]
方法 #2:使用列表理解 + isinstance()
上述功能的组合可以用来解决这个问题。在此,我们使用类似于上述方法的速记方法执行类似的任务。
Python3
# Python3 code to demonstrate working of
# Unlist Single Valued Dictionary List
# Using list comprehension + isinstance()
# initializing list
test_list = [{'Gfg': 1,
'is': [{'a': 2, 'b': 3}]},
{'best': [{'c': 4, 'd': 5}],
'CS': 6}]
# printing original list
print("The original list is : " + str(test_list))
# Using list comprehension + isinstance()
# Similar way as above, extracting first element of list
res = [{key: val[0] if isinstance(val, list) else val
for key, val in sub.items()}
for sub in test_list]
# printing result
print("The converted Dictionary list : " + str(res))
输出 :
The original list is : [{'Gfg': 1, 'is': [{'b': 3, 'a': 2}]}, {'CS': 6, 'best': [{'d': 5, 'c': 4}]}]
The converted Dictionary list : [{'Gfg': 1, 'is': {'b': 3, 'a': 2}}, {'CS': 6, 'best': {'d': 5, 'c': 4}}]