简体   繁体   中英

Iterate Through Python Dict for Specific Values

I am using Python 3.6 and I have a dictionary like so:

{
    "TYPE": {
        "0": "ELECTRIC",
        "1": "ELECTRIC",
        "2": "ELECTRIC",
        "3": "ELECTRIC",
        "4": "TELECOMMUNICATIONS"
    },
    "ID": {
        "0": 13,
        "1": 13,
        "2": 13,
        "3": 13,
        "4": 24
    },
    "1/17/2019": {
        "0": 23,
        "1": 23,
        "2": 23,
        "3": 23,
        "4": 1
    },
    "DATE": {
        "0": "1/17/2019",
        "1": "2/28/2019",
        "2": "3/5/2019",
        "3": "3/28/2019",
        "4": "1/1/2019"
    }
}

How can I iterate through that and access the values of only Utility Type and ID ? My goal is to append them to a list of lists like so [[ELECTRIC, 13], [ELECTRIC, 13], ...]

Up to this point I have been able to access the values like so:

for key, value in addresses.items():
    if key == 'UTILITY TYPE':
        for k, v in value.items():
            print(v)
    elif key == 'ID':
        for k, v in value.items():
            print(v)

but I can't figure out how to append the value of v to my list.

Solution

You could do this using pandas library. Also, consider trying pd.DataFrame(d) to see if that could be of any use to you (since I don't know your final usecase).

import pandas as pd

# d is your dictionary
df = pd.DataFrame(d).T
columns = df.columns
labels = df.index.tolist()
print('labels: {}\n'.format(labels))
[df[x].tolist() for x in columns]

Output :

labels: ['TYPE', 'ID', '1/17/2019', 'DATE']

[['ELECTRIC', 13, 23, '1/17/2019'],
 ['ELECTRIC', 13, 23, '2/28/2019'],
 ['ELECTRIC', 13, 23, '3/5/2019'],
 ['ELECTRIC', 13, 23, '3/28/2019'],
 ['TELECOMMUNICATIONS', 24, 1, '1/1/2019']]

Dummy Data

d = {
    "TYPE": {
        "0": "ELECTRIC",
        "1": "ELECTRIC",
        "2": "ELECTRIC",
        "3": "ELECTRIC",
        "4": "TELECOMMUNICATIONS"
    },
    "ID": {
        "0": 13,
        "1": 13,
        "2": 13,
        "3": 13,
        "4": 24
    },
    "1/17/2019": {
        "0": 23,
        "1": 23,
        "2": 23,
        "3": 23,
        "4": 1
    },
    "DATE": {
        "0": "1/17/2019",
        "1": "2/28/2019",
        "2": "3/5/2019",
        "3": "3/28/2019",
        "4": "1/1/2019"
    }
}
output = []
for key in d["TYPE"]:
    temp = [d["TYPE"][key], d["ID"][key]]
    output.append(temp)

OR

x = [[d["TYPE"][key], d["ID"][key]] for key in d["TYPE"]]

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