简体   繁体   中英

Get only the first two key-value pairs in a python dictionary

I have a list of dictionaries and I would like to iterate through the items in the dictionary and get the first 2 key-value pairs.

#my python dictionary
hunghang = {'fname':'alain', 'lname':'banilad', 'age': 26, 'city':'tokyo'}
charding = {'fname':'rio', 'lname':'talle', 'age': 23, 'city':'berlin'}
mat = {'fname':'professor', 'lname':'steeley', 'age': 29, 'city':'lisbon'}
nicole = {'fname':'denver', 'lname':'aguilar', 'age': 25, 'city':'nairobi'}

#my list of dictionaries
listofdict = [hunghang, charding, mat, nicole]

Now I would like to have a display similar to this:

Information for < fname + lname > are:

  1. < key-value pair #3 >
  2. < key-value pair #4 >

The only thing I have done so far is to iterate through the list, and iterate through the individual dictionaries in the list like this:

for members in listofdict:
    for (info, value) in members.items():
        if info == 'fname':
            first_name = members[info]
            continue

        if info == 'lname':
            last_name = members[info]
            continue

        if first_name and last_name:
            full_name = f"{first_name} {last_name}"
        else:
            continue
        print(f"Info for {full_name.title()} are:")
        print(f"\t{info} : {value.upper() if value is str else value}")

But it is displaying quite differently than I would like for it to.

Info for Alain Banilad are:
    age : 26 
Info for Alain Banilad are:
    city : tokyo 
Info for Rio Talle are:
    age : 23 
Info for Rio Talle are:
    city : berlin 
Info for Professor Steeley are:
    age : 29 Info for
 Professor Steeley are:
    city : lisbon 
Info for Denver Aguilar are:
    age : 25 
Info for Denver Aguilar are:
    city : nairobi

Now my question is: Is there a way to iterate through the dictionary, get < fname + lname > combination (first two key-value pairs) and have it printed to console with the formatting that I have intended?

Don't iterate over the items to get the full name; you clearly know which values you expect and want, so use them.

for members in listofdict:
    full_name = f'{members["first_name"]} {members["last_name"]}'
    print(f"Info for {full_name.title()} are:")

    for (info, value) in members.items():
        if info == 'fname' or info == 'lastname':
            continue
        print(f"\t{info} : {value.upper() if value is str else value}")

Are you not missing the real point of dictionary? As it stores items against keys, you can always access items by key.

for member in listofdict:
    print(f"Dict for => {member['fname']} {member['lname']}")    

Obviously along with this you may extract other information and print as you wish.

Give try like below.

hunghang = {'fname':'alain', 'lname':'banilad', 'age': 26, 'city':'tokyo'}
charding = {'fname':'rio', 'lname':'talle', 'age': 23, 'city':'berlin'}
mat = {'fname':'professor', 'lname':'steeley', 'age': 29, 'city':'lisbon'}
nicole = {'fname':'denver', 'lname':'aguilar', 'age': 25, 'city':'nairobi'}

listofdict = [hunghang, charding, mat, nicole]
print(repr(listofdict))

listoftuples = []
for item in listofdict:
    finame = item['fname']
    lname = item['lname']
    nametuple = (finame,lname)
    listoftuples.append(nametuple)


# Get the values like below,
print(repr(listoftuples))


# Get the values like below,
print(repr(listoftuples[0]))
print(repr(listoftuples[2]))
print(repr(listoftuples[3]))
print(repr(listoftuples[4]))

I think you might be misunderstanding the concept of dictionaries on python: there is no fixed order to the elements, ie there is no 'first' or 'second' value pair. In fact the sequence of the elements might be changed by python. Instead you access the data using the keys stored in the dictionary.

It allows a very lean code for what you have in mind:

#my python dictionary
hunghang = {'fname':'alain', 'lname':'banilad', 'age': 26, 'city':'tokyo'}
charding = {'fname':'rio', 'lname':'talle', 'age': 23, 'city':'berlin'}
mat = {'fname':'professor', 'lname':'steeley', 'age': 29, 'city':'lisbon'}
nicole = {'fname':'denver', 'lname':'aguilar', 'age': 25, 'city':'nairobi'}

#my list of dictionaries
listofdict = [hunghang, charding, mat, nicole]

for members in listofdict:
        print("Info for {} {} are:".format(
                members["fname"], members["lname"]))
        print("\tage: {}".format(members["age"]))
        print("\tcity: {}".format(members["city"]))

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