簡體   English   中英

python 字典操作添加所有可能的字段

[英]python dictionary operation to add all possible fields

我有一個名為attributeslist ,其中包含所有可能的字段。 像這樣:

attributes = [
    'name',
    'phone_no',
    'address',
    'hobby',
]

我還有一些dictionaries ,其中包含一些key-value對,並且keys始終是attributes列表的子集。 一本這樣的dictionary是:

my_dict = {'name': "Kanchon Gharami", 'address': "Bangladesh"}

在此字典中,僅存在兩個keysnameaddress ), attribute列表中的兩個字段(電話號碼和hobby )的phone_no不存在。

如果沒有給出值,我需要將其轉換為將所有可能的字段作為key和值NAN 像這樣的東西:

my_dict = {'name': "Kanchon Gharami", 'phone_no' : "NAN", 'address': "Bangladesh", 'hobby' : "NAN"}

請告訴我如何用 Python 做到這一點?

我建議你使用defaultdict

否則,您可以遍歷您的attributes列表並將它們作為鍵添加到您的字典中。

有一個基本字典,然后更新你在my_dict中的字段

attributes = [
    'name',
    'phone_no',
    'address',
    'hobby',
]

my_dict = {'name': "Kanchon Gharami", 'address': "Bangladesh"}
attributes_tpl = [('name', "NaN"), ('phone_no', "NaN"), ('address', "NaN"), ('hobby', "NaN")]
base_dict = dict(attributes_tpl)
base_dict.update(my_dict)
print(base_dict)

您可以使用字典理解:

attributes = [
'name',
'phone_no',
'address',
'hobby',
]
#the dictionary has to be filled with some attrs
dictionary = {attr:"NAN" if attr not in dictionary.keys() else dictionary[attr] for attr in attributes}

你可以這樣做:

attributes = [
'name',
'phone_no',
'address',
'hobby',
]
dictionary = dict()
for attr in attribute:
    if attr not in dictionary:
        dictionary[attr] = "NAN"

這是我將為您准備的一個小例子,如果我誤解了這個問題,請告訴我。

myAttributes = [“name”, “phone”, “address”, “hobby”]
myDict = {“name”: “Kanchon”, “address”: “myHouse”}
newDict = dict()
for item in myAttributes:
   for key, value in myDict.items():
       if key == item:
          newDict[key] = value
          continue
       newDict[key] = None

恐怕我無法對此進行測試,但我很想聽聽它是否有效。

attributes = [
    'name',
    'phone_no',
    'address',
    'hobby',
]
my_dict = {'name': "Kanchon Gharami", 'phone_no' : "NAN", 'address': "Bangladesh", 'hobby' : "NAN"}

mydict=dict()

for l in attributes:
    if l=='phone_no':
        mydict[l]="NAN"
    else:
        mydict[l]="test"
print(mydict)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM