簡體   English   中英

使用舊詞典中的特定鍵創建新詞典

[英]Create new dictionary with specific keys from old dictionary

我想制作一個新字典,為字典的所有行打印一個包含uuid,名稱,網站和電子郵件地址的新對象,這些行具有所有這四個屬性的值。

我以為我在代碼中對下面的電子郵件,名稱和網站做了此操作,但是我注意到有時名稱或電子郵件不會打印出來(因為它們缺少值),我該如何刪除它們? 另外,uuid在嵌套字典的外部,我如何也將其添加到新字典中?

我在下面的代碼中附加了代碼和元素。

new2 = {}

for i in range (0, len(json_file)):
    try: 
        check = json_file[i]['payload']
        new = {k: v for k, v in check.items() if v is not None}
        new2 = {k: new[k] for k in new.keys() & {'name', 'website', 'email'}}
        print(new2)
    except:
        continue

字典樣本:

{
   "payload":{
      "existence_full":1,
      "geo_virtual":"[\"56.9459720|-2.1971226|20|within_50m|4\"]",
      "latitude":"56.945972",
      "locality":"Stonehaven",
      "_records_touched":"{\"crawl\":8,\"lssi\":0,\"polygon_centroid\":0,\"geocoder\":0,\"user_submission\":0,\"tdc\":0,\"gov\":0}",
      "address":"The Lodge, Dunottar",
      "email":"dunnottarcastle@btconnect.com",
      "existence_ml":0.5694238217658721,
      "domain_aggregate":"",
      "name":"Dunnottar Castle",
      "search_tags":[
         "Dunnottar Castle Aberdeenshire",
         "Dunotter Castle"
      ],
      "admin_region":"Scotland",
      "existence":1,
      "category_labels":[
         [
            "Landmarks",
            "Buildings and Structures"
         ]
      ],
      "post_town":"Stonehaven",
      "region":"Kincardineshire",
      "review_count":"719",
      "geocode_level":"within_50m",
      "tel":"01569 762173",
      "placerank":65,
      "longitude":"-2.197123",
      "placerank_ml":37.27916073464469,
      "fax":"01330 860325",
      "category_ids_text_search":"",
      "website":"http://www.dunnottarcastle.co.uk",
      "status":"1",
      "geocode_confidence":"20",
      "postcode":"AB39 2TL",
      "category_ids":[
         108
      ],
      "country":"gb",
      "_geocode_quality":"4"
   },
   "uuid":"3867aaf3-12ab-434f-b12b-5d627b3359c3"
}

嘗試使用dict.get()方法:

def new_dict(input_dict, keys, fallback='payload'):
    ret = dict()
    for key in keys:
        val = input_dict.get(key) or input_dict[fallback].get(key)
        if val:
            ret.update({key:val})
    if len(ret) == 4:   # or you could do: if set(ret.keys()) == set(keys):
        print(ret)

for dicto in json_file:
    new_dict(dicto, ['name','website','email','uuid'])
{'name': 'Dunnottar Castle', 'website': 'http://www.dunnottarcastle.co.uk', 'email': 'dunnottarcastle@btconnect.com', 'uuid': '3867aaf3-12ab-434f-b12b-5d627b3359c3'}

暫無
暫無

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

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