简体   繁体   中英

convert multiple values and a key into dictionary in Python

I want to convert the following data into dictionary, where name is key and all int are values.

  • Mary Lee,39,169,100
  • James Clark,68,170,105
  • Eric Roth,66,161,103
  • William Brown,45,180,85

Use the name as the key as you said. You should make a tuple of all the numbers and use it for the value.

To create a dictionary in your code, you need the curly brackets {}

The general form for declaring a dictionary is

{ key1: value1, key2: value2 }

Dictionaries only support 1 value for each key. In this case, you want multiple values, so you can use a tuple using the round brackets () . A tuple groups multiple values together into single value, which can then be used in the dictionary.

{ key1: (v11,v12,v13), key2: (v21,v22,v23) }

Using your values, you'd have something like this, I have added line breaks to make it more readable, but these are optional.

people = {
    "Mary Lee": (39,169,100),
    "James Clark": (68,170,105),
    "Eric Roth": (66,161,103),
    "William Brown": (45,180,805)
    }

If you then wanted to add more values to this dictionary:

people["Colin Stevens"] = (55,186,100)

However, I would strongly suggest you use python's Object Orientation to give more meaning to these values.

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