简体   繁体   中英

python print value from two different dictionary

I have a basic question, but I couldn't find a way to solve it. I have 2 dictionary, with the same key but different value. I want to print the key with its 2 values in one line. And the second key with its values in a line below

I tried something like that:

d1 = {12345: "0102", 123456: "888"}
d2 = {12345: "priv", 123456: "public"}

for value in d1.items():
    x = value
    for key, value in d2.items():
        y = value
        print(f"car plate{d1.keys()} phone:{x} type: {y}")

And i got this result:

car platedict_keys([12345, 123456]) phone:(12345, '0102') type: priv
car platedict_keys([12345, 123456]) phone:(12345, '0102') type: public
car platedict_keys([12345, 123456]) phone:(123456, '888') type: priv
car platedict_keys([12345, 123456]) phone:(123456, '888') type: public

My goal is to get something like this:

car 12345 - phone: 0102 type: priv
car 123456 - phone: 888 type: public

Any suggestions how to do it?

>>> d1 = {12345: "0102", 123456: "888"}
>>> d2 = {12345: "priv", 123456: "public"}
>>> for key in d1:
...     print(f"car {key} - phone: {d1[key]} type: {d2[key]}")
...
car 12345 - phone: 0102 type: priv
car 123456 - phone: 888 type: public

You can achieve what you want with this but it would be so much better if you store the data in only one dictionary.

car_plates = {
  12345: {
    "phone": "0102",
    "type": "priv"
  },
  123456: {
    "phone": "888",
    "type": "public"
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM