为字典中的一个键追加多个值

发布于 2024-09-08 17:34:20 字数 636 浏览 3 评论 0原文

我是 python 新手,我有每年的年份和值列表。我想要做的是检查字典中是否已存在该年份,如果存在,则将该值附加到特定键的值列表中。

例如,我有一个年份列表,每年都有一个值:

2010  
2  
2009  
4  
1989  
8  
2009  
7  

我想要做的是以年份作为键,以那些个位数作为值来填充字典。但是,如果我将 2009 年列出两次,我想将第二个值附加到该字典中的值列表中,所以我想要:

2010: 2  
2009: 4, 7  
1989: 8  

现在我有以下内容:

d = dict()  
years = []  

(get 2 column list of years and values)

for line in list:    
    year = line[0]   
    value = line[1]  

for line in list:  
    if year in d.keys():  
        d[value].append(value)  
    else:  
        d[value] = value  
        d[year] = year  

I am new to python and I have a list of years and values for each year. What I want to do is check if the year already exists in a dictionary and if it does, append the value to that list of values for the specific key.

So for instance, I have a list of years and have one value for each year:

2010  
2  
2009  
4  
1989  
8  
2009  
7  

What I want to do is populate a dictionary with the years as keys and those single digit numbers as values. However, if I have 2009 listed twice, I want to append that second value to my list of values in that dictionary, so I want:

2010: 2  
2009: 4, 7  
1989: 8  

Right now I have the following:

d = dict()  
years = []  

(get 2 column list of years and values)

for line in list:    
    year = line[0]   
    value = line[1]  

for line in list:  
    if year in d.keys():  
        d[value].append(value)  
    else:  
        d[value] = value  
        d[year] = year  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

森林很绿却致人迷途 2024-09-15 17:34:20

如果我可以重新表述你的问题,你想要的是一个以年份为键的字典,以及每年的一个数组,其中包含与该年份相关的值列表,对吧?我是这样做的:

years_dict = dict()

for line in list:
    if line[0] in years_dict:
        # append the new number to the existing array at this slot
        years_dict[line[0]].append(line[1])
    else:
        # create a new array in this slot
        years_dict[line[0]] = [line[1]]

在years_dict中你最终应该得到一个如下所示的字典:

{
    "2010": [2],
    "2009": [4,7],
    "1989": [8]
}

一般来说,创建“并行数组”是一种糟糕的编程实践,其中项目通过具有相同的索引,而不是包含它们的容器的正确子项。

If I can rephrase your question, what you want is a dictionary with the years as keys and an array for each year containing a list of values associated with that year, right? Here's how I'd do it:

years_dict = dict()

for line in list:
    if line[0] in years_dict:
        # append the new number to the existing array at this slot
        years_dict[line[0]].append(line[1])
    else:
        # create a new array in this slot
        years_dict[line[0]] = [line[1]]

What you should end up with in years_dict is a dictionary that looks like the following:

{
    "2010": [2],
    "2009": [4,7],
    "1989": [8]
}

In general, it's poor programming practice to create "parallel arrays", where items are implicitly associated with each other by having the same index rather than being proper children of a container that encompasses them both.

離人涙 2024-09-15 17:34:20

您最好使用 collections.defaultdict (添加在Python 2.5)。这允许您指定缺失键的默认对象类型(例如 list)。

因此,您不需要先创建一个不存在的键,然后附加到该键的值,而是省去中间人,直接附加到不存在的键以获得所需的结果。

使用数据的简单示例:

>>> from collections import defaultdict
>>> data = [(2010, 2), (2009, 4), (1989, 8), (2009, 7)]
>>> d = defaultdict(list)
>>> d
defaultdict(<type 'list'>, {})
>>> for year, month in data:
...     d[year].append(month)
... 
>>> d
defaultdict(<type 'list'>, {2009: [4, 7], 2010: [2], 1989: [8]})

这样您就不必担心是否看到与年份相关的数字。您只需添加并忘记,因为知道丢失的键将永远是一个列表。如果一个键已经存在,那么它只会被附加到。

You would be best off using collections.defaultdict (added in Python 2.5). This allows you to specify the default object type of a missing key (such as a list).

So instead of creating a key if it doesn't exist first and then appending to the value of the key, you cut out the middle-man and just directly append to non-existing keys to get the desired result.

A quick example using your data:

>>> from collections import defaultdict
>>> data = [(2010, 2), (2009, 4), (1989, 8), (2009, 7)]
>>> d = defaultdict(list)
>>> d
defaultdict(<type 'list'>, {})
>>> for year, month in data:
...     d[year].append(month)
... 
>>> d
defaultdict(<type 'list'>, {2009: [4, 7], 2010: [2], 1989: [8]})

This way you don't have to worry about whether you've seen a digit associated with a year or not. You just append and forget, knowing that a missing key will always be a list. If a key already exists, then it will just be appended to.

人间不值得 2024-09-15 17:34:20

您可以使用setdefault

for line in list:  
    d.setdefault(year, []).append(value)

这是有效的,因为 setdefault 返回列表并将其设置在字典中,并且因为列表是可变的,所以附加到 setdefault 返回的版本与将其附加到字典本身内的版本相同。如果这有任何意义的话。

You can use setdefault.

for line in list:  
    d.setdefault(year, []).append(value)

This works because setdefault returns the list as well as setting it on the dictionary, and because a list is mutable, appending to the version returned by setdefault is the same as appending it to the version inside the dictionary itself. If that makes any sense.

虐人心 2024-09-15 17:34:20
d = {} 

# import list of year,value pairs

for year,value in mylist:
    try:
        d[year].append(value)
    except KeyError:
        d[year] = [value]

Python 之道——获得宽恕比请求许可更容易!

d = {} 

# import list of year,value pairs

for year,value in mylist:
    try:
        d[year].append(value)
    except KeyError:
        d[year] = [value]

The Python way - it is easier to receive forgiveness than ask permission!

深海里的那抹蓝 2024-09-15 17:34:20

这是使用 not in 运算符执行此操作的另一种方法:

# define an empty dict
years_dict = dict()

for line in list:
    # here define what key is, for example,
    key = line[0]
    # check if key is already present in dict
    if key not in years_dict:
        years_dict[key] = []
    # append some value 
    years_dict[key].append(some.value)

Here is an alternative way of doing this using the not in operator:

# define an empty dict
years_dict = dict()

for line in list:
    # here define what key is, for example,
    key = line[0]
    # check if key is already present in dict
    if key not in years_dict:
        years_dict[key] = []
    # append some value 
    years_dict[key].append(some.value)
最美的太阳 2024-09-15 17:34:20

如果将这些值放入元组列表中会更容易。为此,您可以使用列表切片和 zip 函数。

data_in = [2010,2,2009,4,1989,8,2009,7]
data_pairs = zip(data_in[::2],data_in[1::2])

Zip 获取任意数量的列表(在本例中为 data_in 的偶数和奇数条目),并将它们放在一起形成一个元组。

现在我们可以使用setdefault方法。

data_dict = {}
for x in data_pairs:
    data_dict.setdefault(x[0],[]).append(x[1])

setdefault 接受一个键和一个默认值,并返回关联值,或者如果没有当前值,则返回默认值。在这种情况下,我们将获得一个空列表或填充列表,然后将当前值附加到其中。

It's easier if you get these values into a list of tuples. To do this, you can use list slicing and the zip function.

data_in = [2010,2,2009,4,1989,8,2009,7]
data_pairs = zip(data_in[::2],data_in[1::2])

Zip takes an arbitrary number of lists, in this case the even and odd entries of data_in, and puts them together into a tuple.

Now we can use the setdefault method.

data_dict = {}
for x in data_pairs:
    data_dict.setdefault(x[0],[]).append(x[1])

setdefault takes a key and a default value, and returns either associated value, or if there is no current value, the default value. In this case, we will either get an empty or populated list, which we then append the current value to.

不打扰别人 2024-09-15 17:34:20

如果您想要(几乎)一行:

from collections import deque

d = {}
deque((d.setdefault(year, []).append(value) for year, value in source_of_data), maxlen=0)

使用 dict.setdefault ,您可以将“检查密钥是否已存在,如果不存在则创建一个新列表”的想法封装到单个调用中。这允许您编写一个生成器表达式,该表达式由 deque 尽可能高效地使用,因为队列长度设置为零。双端队列将立即被丢弃,结果将在d中。

这只是我为了好玩而做的事情。我不建议使用它。在某个时间和地点可以通过双端队列消耗任意可迭代对象,但这绝对不是这样。

If you want a (almost) one-liner:

from collections import deque

d = {}
deque((d.setdefault(year, []).append(value) for year, value in source_of_data), maxlen=0)

Using dict.setdefault, you can encapsulate the idea of "check if the key already exists and make a new list if not" into a single call. This allows you to write a generator expression which is consumed by deque as efficiently as possible since the queue length is set to zero. The deque will be discarded immediately and the result will be in d.

This is something I just did for fun. I don't recommend using it. There is a time and a place to consume arbitrary iterables through a deque, and this is definitely not it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文