![](/img/trans.png)
[英]one liner to create a dictionnary with values of list an an other one. Is it possible?
[英]How to split list inside a dictionnary to create a new one?
我一直在努力奮斗,
我的字典格式如下
dict = {a:[element1, element2, element3], b:[element4, element5, element6]...}
我要使用以下格式的新字典
newdict = {a:element1, b:element4...}
這意味着僅保留每個值包含的列表的第一個元素。
您可以使用字典理解 :
{k: v[0] for k, v in d.items()}
# {'a': 'element1', 'b': 'element4'}
希望這會有所幫助。
我想在覆蓋鍵值之前檢查字典中是否有鍵。
dict = {a:[element1, element2, element3], b:[element4, element5, element6]}
Python 2
newDict = {}
for k, v in dict.iteritems():
if k not in newDict:
# add the first list value to the newDict's key
newDick[k] = v[0]
Python 3
newDict = {}
for k, v in dict.items():
if k not in newDict:
# add the first list value to the newDict's key
newDick[k] = v[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.