arkanjie
arkanjie

Reputation: 73

Modify dictionary to add new keys and values to existing entries

here is me again asking for help in order to keep learning Python. Thanks in advance to everyone who takes the time to contribute here.

So, let's say I have this dictionary:

{
    "Pres": "John",
    "King": "Henri"
}

And what I want is to add a "sub dictionary" to each entry, getting an output like this

{
  "Pres": {
    "Name": "John",
    "link": "example.com"
  },
  "King": {
    "Name": "Henri",
    "link": "example2.com"
  }
}

Upvotes: 1

Views: 82

Answers (2)

Tanmay Chavan
Tanmay Chavan

Reputation: 345

Something like this would work

d = {
    "Pres": "John",
    "King": "Henri"
}

for key in d:
    d[key] = {
        'Name': d[key],
        'link': 'dummyLink'
    }

print(d)

You can replace dummy link by something else

Upvotes: 3

ali
ali

Reputation: 537

You can loop over the old dict containing the names and a list of urls and create new dictionaries like this:

names_dict = {
    "Pres": "John",
    "King": "Henri",
}
urls = ["example.com", "example2.com"]
new_dict = {}

for (key, name), url in zip(names_dict.items(), urls):
    new_dict[key] = {"Name": name, "link": url}

print(new_dict)

Upvotes: 2

Related Questions