python как объединить два словаря - PullRequest
0 голосов
/ 01 апреля 2020

После долгих поисков все направляли ответ на этот пост: [ Как объединить два словаря в одном выражении?

Но я хочу объединить два словаря и не сливаются. Оба моих словаря имеют один и тот же ключ, поэтому, когда я использую tempdict.update(data), он заменяет мои данные, а не добавляет их к нему. Словари выглядят так:

{
  "symbol" : "AAPL",
  "profile" : {
    "price" : 254.29,
    "beta" : "1.228499",
    "volAvg" : "49330169",
    "mktCap" : "1.11264072E12",
    "lastDiv" : "2.92",
    "range" : "170.27-327.85",
    "changes" : -0.52,
    "changesPercentage" : "(-0.20%)",
    "companyName" : "Apple Inc.",
    "exchange" : "Nasdaq Global Select",
    "industry" : "Computer Hardware",
    "website" : "http://www.apple.com",
    "description" : "Apple Inc is designs, manufactures and markets mobile communication and media devices and personal computers, and sells a variety of related software, services, accessories, networking solutions and third-party digital content and applications.",
    "ceo" : "Timothy D. Cook",
    "sector" : "Technology",
    "image" : "https://financialmodelingprep.com/images-New-jpg/AAPL.jpg"
  }
}
{
  "symbol" : "FB",
  "profile" : {
    "price" : 166.8,
    "beta" : "1.062394",
    "volAvg" : "21198830",
    "mktCap" : "4.75455062E11",
    "lastDiv" : "0",
    "range" : "137.1-224.2",
    "changes" : 0.85,
    "changesPercentage" : "(+0.51%)",
    "companyName" : "Facebook Inc.",
    "exchange" : "Nasdaq Global Select",
    "industry" : "Online Media",
    "website" : "http://www.facebook.com",
    "description" : "Facebook Inc is the world's largest online social network. Its products are Facebook, Instagram, Messenger, WhatsApp, and Oculus. Its products enable people to connect and share through mobile devices and personal computers.",
    "ceo" : "Mark Zuckerberg",
    "sector" : "Technology",
    "image" : "https://financialmodelingprep.com/images-New-jpg/FB.jpg"
  }
}

Я хочу, чтобы это выглядело так:

{
  "companyProfiles" : [ {
    "symbol" : "AAPL",
    "profile" : {
      "price" : 254.29,
      "beta" : "1.228499",
      "volAvg" : "49330169",
      "mktCap" : "1.11264072E12",
      "lastDiv" : "2.92",
      "range" : "170.27-327.85",
      "changes" : -0.52,
      "changesPercentage" : "(-0.20%)",
      "companyName" : "Apple Inc.",
      "exchange" : "Nasdaq Global Select",
      "industry" : "Computer Hardware",
      "website" : "http://www.apple.com",
      "description" : "Apple Inc is designs, manufactures and markets mobile communication and media devices and personal computers, and sells a variety of related software, services, accessories, networking solutions and third-party digital content and applications.",
      "ceo" : "Timothy D. Cook",
      "sector" : "Technology",
      "image" : "https://financialmodelingprep.com/images-New-jpg/AAPL.jpg"
    }
  }, {
    "symbol" : "FB",
    "profile" : {
      "price" : 166.8,
      "beta" : "1.062394",
      "volAvg" : "21198830",
      "mktCap" : "4.75455062E11",
      "lastDiv" : "0",
      "range" : "137.1-224.2",
      "changes" : 0.85,
      "changesPercentage" : "(+0.51%)",
      "companyName" : "Facebook Inc.",
      "exchange" : "Nasdaq Global Select",
      "industry" : "Online Media",
      "website" : "http://www.facebook.com",
      "description" : "Facebook Inc is the world's largest online social network. Its products are Facebook, Instagram, Messenger, WhatsApp, and Oculus. Its products enable people to connect and share through mobile devices and personal computers.",
      "ceo" : "Mark Zuckerberg",
      "sector" : "Technology",
      "image" : "https://financialmodelingprep.com/images-New-jpg/FB.jpg"
    }
  } ]
}

Это то, что я получил до сих пор, но я знаю, что проблема в том, с .update:

tempdict = dict()
for symbol in ["AAPL","FB"]:
    with requests.get("https://financialmodelingprep.com/api/v3/company/profile/"+ symbol) as url:
        data_string = url.content.decode()
        data =json.loads(data_string)
    tempdict.update(data)
    print(tempdict)

1 Ответ

2 голосов
/ 01 апреля 2020

Вы можете создать словарь с новым ключом "companyProfiles", сопоставленным с пустым списком. Затем на каждой итерации (для каждой symbol) вы можете добавить к этому списку свой словарь ответов JSON, то есть:

import json
import requests
tempdict = {"companyProfiles": []}
for symbol in ["AAPL","FB"]:
    with requests.get("https://financialmodelingprep.com/api/v3/company/profile/"+ symbol) as url:
        data_string = url.content.decode()
        data =json.loads(data_string)
    tempdict["companyProfiles"].append(data)
print(tempdict)

Выходы:

{'companyProfiles': [{'profile': {'beta': '1.228499',
                                  'ceo': 'Timothy D. Cook',
                                  'changes': -0.52,
                                  'changesPercentage': '(-0.20%)',
                                  'companyName': 'Apple Inc.',
                                  'description': 'Apple Inc is designs, '
                                                 'manufactures and markets '
                                                 'mobile communication and '
                                                 'media devices and personal '
                                                 'computers, and sells a '
                                                 'variety of related software, '
                                                 'services, accessories, '
                                                 'networking solutions and '
                                                 'third-party digital content '
                                                 'and applications.',
                                  'exchange': 'Nasdaq Global Select',
                                  'image': 'https://financialmodelingprep.com/images-New-jpg/AAPL.jpg',
                                  'industry': 'Computer Hardware',
                                  'lastDiv': '2.92',
                                  'mktCap': '1.11264072E12',
                                  'price': 254.29,
                                  'range': '170.27-327.85',
                                  'sector': 'Technology',
                                  'volAvg': '49330169',
                                  'website': 'http://www.apple.com'},
                      'symbol': 'AAPL'},
                     {'profile': {'beta': '1.062394',
                                  'ceo': 'Mark Zuckerberg',
                                  'changes': 0.85,
                                  'changesPercentage': '(+0.51%)',
                                  'companyName': 'Facebook Inc.',
                                  'description': "Facebook Inc is the world's "
                                                 'largest online social '
                                                 'network. Its products are '
                                                 'Facebook, Instagram, '
                                                 'Messenger, WhatsApp, and '
                                                 'Oculus. Its products enable '
                                                 'people to connect and share '
                                                 'through mobile devices and '
                                                 'personal computers.',
                                  'exchange': 'Nasdaq Global Select',
                                  'image': 'https://financialmodelingprep.com/images-New-jpg/FB.jpg',
                                  'industry': 'Online Media',
                                  'lastDiv': '0',
                                  'mktCap': '4.75455062E11',
                                  'price': 166.8,
                                  'range': '137.1-224.2',
                                  'sector': 'Technology',
                                  'volAvg': '21198830',
                                  'website': 'http://www.facebook.com'},
                      'symbol': 'FB'}]}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...