I have a nested dict as follows:
list = { "A" : [ "1", "2", "3" ], "B" : [ "2" ], "C" : [ "1", "2" ] }
I want to concatenate dictionary keys and list values as follows:
[ "A.1", "A.2", "A.3", "B.2", "C.1", "C.2" ]
Any suggestions?
You can try the following code:
list = { "A" : [ "1", "2", "3" ], "B" : [ "2" ], "C" : [ "1", "2" ] }
data = []
for key, values in list.items():
for value in values:
data.append("{0}.{1}".format(key,value))
print(data)
# Output ['A.1', 'A.2', 'A.3', 'B.2', 'C.1', 'C.2']
lst = {"A": ["1", "2", "3"], "B": ["2"], "C": ["1", "2"]}
result = ["{}.{}".format(key, val)
for key, vals in lst.items()
for val in vals]
print(result)
new_list = []
for ks, vs in list.items():
for v in vs:
new_list.append('.'.join([ks, v]))
print(new_list)
# output
['A.1', 'A.2', 'A.3', 'C.1', 'C.2', 'B.2']
用字典的对值循环,然后将每个单独的值附加到空列表中。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.