首页 > 解决方案 > 使用旧字典中的特定键创建新字典

问题描述

我想制作一个新的字典,它为我的字典的所有行打印一个包含 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"
}

标签: python

解决方案


尝试使用 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'}

推荐阅读